0

I format numbers using jqnumformatter plugin. Everything is fine with that but I'm having problems on removing the commas. I used .each() to loop through all the inputs which has commas on it. But in this case I need to click on the next button twice so that all the commas on the numbers will be removed.

<script>
$(function(){

    $("#next").click(function(){//unformats the numbers

        $("input[data-toformat=format]").each(function(){
            var formatted = $(this).val();
            var unformatted = formatted.replace(",", "");
            $(this).val(unformatted);
        });

    });


});
</script>

<input type="text" id="num" data-toformat="format"  autofocus/>
<input type="text" id="num2" data-toformat="format" />
<input type="button" id="next" value="next">
<input type="button" id="back" value="back">

Do you have a better way on doing this?It really fails to unformat the numbers all at once if I have 2 or more commas on each of the numbers.

1 Answer 1

5

The problem is in the way you are calling the .replace() method:

var unformatted = formatted.replace(",", ""); 

If you pass a string as the first parameter it only replaces the first occurrence. If you pass a regular expression you can set the regex "global" flag to replace all occurrences:

var unformatted = formatted.replace(/,/g, "");

Note that your code can be simplified quite a bit because you don't really need the local variables:

$(this).val( $(this).val().replace(/,/g, "") );

But it can be simplified even further because if you pass a function to the .val() method you don't even need the .each() loop:

$(function(){
   $("#next").click(function(){
       //unformats the numbers
       $("input[data-toformat=format]").val(function(i, oldVal){
           return oldVal.replace(/,/g, "");
       });
   });
});

This syntax for .val() will pass the old (current) value of each element to the function you supply, setting the new value to the return from that function.

Sign up to request clarification or add additional context in comments.

1 Comment

Will what work for dynamically generated elements? The .replace() part works on any string. The .val() part (or the .each() from your code) works on any elements in the jQuery object that you run it on, i.e., any elements that matched the selector at the time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.