Skip to content Skip to sidebar Skip to footer

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: ).keyup(function(event) { // skip for arrow keysif(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, ","); }); });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text"name= "name1"id="id1"><inputtype="text"name= "name1"id="id2">

Solution 2:

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, ",");
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text"name="name1"id="id1"class="foo" /><inputtype="text"name="name2"id="id2"class="foo" />

Post a Comment for "Adding Comma While Typing In The Text Box"