Webconstructor
Webconstructor

Reputation: 545

jQuery replace with regex not working correctly

I want to exclude all characters which are not a digit or minus.

What strikes me is that I cannot start with a minus or enter it anywhere. Only after digits and using the keyboard arrow button is entering a minus possible.

What I would like is being able to just enter -60 or something the like. What should I change?

$('.minus').keyup(function() {
  var txt = $(this).val();
  var nwtxt = txt.replace(/[^\d-]/ig, "");
  $(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus">

Upvotes: 1

Views: 84

Answers (2)

Joel Harkes
Joel Harkes

Reputation: 11661

I think it's some kind of browser defence meganism that whenever you insert something that is not a number inside a number input field and you request the value from it, it will simply be null/undefined. On type="text" it looks like this is fine.

Also note your cursor is always put at the end of the text, because you replace the text always. So you can't insert a - (dash) before a number with only keyboard interaction. and a dash anywhere but in front of a number is invalid!

You can try to type in -60 in the number field as well but you first need to insert. 60 and then the minus character.

also its better to use $('.minus').input( instead of keyUp, since you can use the mouse to insert values as well (and the scroll wheel).

$('.minus').keyup(function() {
  var txt = $(this).val();
  console.log("value i got:",txt); //i added this logging to see that you didn't get anything on number.
  var nwtxt = txt.replace(/[^\d-]/ig, "");
  if(nwtext !==txt) //add this if statement so your cursor does not constantly jump to the end!
    $(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes  minus" placeholder="number">
<input type="text" maxlength="9" class="tekstvakjes  minus" placeholder="text">

Upvotes: 0

Vijay Mishra
Vijay Mishra

Reputation: 350

Instead of using input type number use text

Upvotes: 3

Related Questions