haitruonginfotech haitruonginfotech - 5 months ago 11
jQuery Question

Error: javascript key in invalid format integer

<input type="text" name="quantity">


I want this is a number(allow 0-9 and -), this is my code:

function update_quantity() {
$(this).val($(this).val().replace(/[^-?\d]/g, ''));
}
$(document).on("change, keyup", "input[type=text])", update_quantity);


Ex:

123 -> valid
-123 -> valid
123- -> invalid
-1-12-123 -> invalid
-123-12 -> invalid


--> error can't auto replace -123-12 to -12312 or 123- to 123, how to fix it

Answer

This seems to be what you are looking for:

https://jsfiddle.net/7vywp5nn/1/

$(document).ready(function() {
  $('input[name=quantity]').on('keyup',function() {
    var v = $(this).val();
    if (!v.match(/^-?[0-9]*$/))
      $(this).val(v.replace(/(?!^-)[^0-9]/g,''));
  });
});

Though I would personally do it on change or blur instead of stripping as user enters. Or better yet, return a visible error and prevent form submit, rather than auto-replace. I really hate form fields that do this sort of thing. Makes for bad UX IMO.

Comments