tenten tenten - 13 days ago 5
HTML Question

Adding comma while typing in the text box

I have a text field. I am writing numbers in the text box. While I am writing I want to add the thousand separator. I found this solution:

HTML:

<input type="text" name= "name1" id="id1" onclick="addComma('id1');">
<input type="text" name= "name1" id="id2" onclick="addComma('id2');">


JQUERY:

function addComma(id){
$("#"+id).keyup(function(event) {

// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;

// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
}


This only works sometimes. Sometimes it doesn't show the comma at all.

Please tell me what is wrong with my code.

Answer

Here is solution that adding comma while typing in the text box. You need to trigger keyup event for every input.

$('input').keyup(function(event) {
    // skip for arrow keys
    if(event.which >= 37 && event.which <= 40) return;

    // format number
    $(this).val(function(index, value) {
      return value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name= "name1" id="id1">
<input type="text" name= "name1" id="id2">

Comments