tenten
tenten

Reputation: 1276

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.

Upvotes: 0

Views: 4257

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

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">

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

I would suggest that you format the input's value on the blur event. If you do this as the user types it would be unexpected behaviour and could cause confusion.

Also note that your HTML has duplicate id attributes which is invalid, and also has an odd mix of jQuery and JS. You should remove the outdated on* event attributes and use unobtrusive event handlers instead. Try this:

$('.foo').blur(function() {
  $(this).val(function(i, v) {
    return v.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" class="foo" />
<input type="text" name="name2" id="id2" class="foo" />

Upvotes: 2

Related Questions