1

I need to replace all non numeric characters in a textare using javascript. Our client wants to remove and non digits e.g 1,330.00 becomes 1330.00.

I can replace all non digits except for the decimal place, but this allows multiple decimal places.

I have a jsbin of the code http://jsbin.com/vetedeca/1/edit?html,output


    $(document).ready(function(){
        $('input').bind('keyup', function() {
          var value = $(this).val()

          value = value.replace(/[^\d\.]+/g,'');

          $(this).val(value);
        })
      })

How can i edit this to remove all non digits except the first occurrence of a decimal place

e.g 1,330.00 becomes 1330.00 1,330.00.00 becomes 1330.00 133o.00d.33 becomes 133.00

Wardy277
  • 33
  • 6

1 Answers1

1

I managed to find a way to deal with the multiple dots issue.

I added another line using .replace() :

$(document).ready(function(){
  $('input').bind('keyup', function() {
  var value = $(this).val()

  value = value.replace(/[^\d\.]+/g,'');
  value = value.replace(/(\..*)\./g,'$1');
  $(this).val(value);
  })
})

This additional line will check if there is a first dot followed by digits, and then followed by another dot.

If it is the case, the replace will keep the existing decimal part and remove the second dot.

Updated jsbin : http://jsbin.com/vetedeca/3/edit?html,output

Theox
  • 1,363
  • 9
  • 20