1

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

7
  • By exclude, you mean remove right? Commented Jan 30, 2017 at 12:59
  • So you want to allow negative numbers only? Commented Jan 30, 2017 at 13:01
  • No, I want to include both negative and positive numbers Commented Jan 30, 2017 at 13:02
  • All other characters must be removed Commented Jan 30, 2017 at 13:02
  • 2
    Make input type as text instead number Commented Jan 30, 2017 at 13:03

2 Answers 2

3

Instead of using input type number use text

Sign up to request clarification or add additional context in comments.

1 Comment

what i was about to say (it is because the number type adds a validation before the keyup event fires, and removes the value if not conform, before if even fires the event)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.