0

I would like to ask something about preventDefault() in jQuery: my problem is when I use preventDefault() inside a condition the method is running before checking my condition is true or not, does anyone know what the problem is?

I already do every way to make my preventDefault() is working when my condition is true, but the reality is not working so right.

This my example code to give everyone more detail about my problem, I hope you all can help me to solve my problem, thanks before.

$("input[name='test']").on({
  keydown: function(event) {
    const selector = event.which;

    if (selector == 69) {
      event.preventDefault();
    } else if (selector == 8) {
      const inputVal = $(this).val();
      const subsVal = inputVal.substr(0, (inputVal.length - 1));

      if (subsVal == '' || subsVal.length == 0) {
        console.log("stop it, it's already empty");
        event.preventDefault(); // => when I use this method is not working perfect, because when the input text length is not zero yet, the method is running then I can't delete it until the input value is empty or zero length
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="test" value="1">
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
ProLuck
  • 331
  • 4
  • 18
  • you can change the event handler to listen to `keyup` instead of `keydown` to let the user remove the text first and trigger the error afterwards – Prikesh Savla Apr 29 '21 at 04:44
  • thanks for answer, but when I use `keyup` the `preventDefault()` is not working, so why I choose `keydown` instead `keyup` – ProLuck Apr 29 '21 at 04:46
  • do you want to prevent the user from deleting the last char? then it works as intended for me in the snippet. – Prikesh Savla Apr 29 '21 at 05:06
  • nope sir, I mean when the my input value is empty or nothing display in my input, the method will be running, for example when the input value have last char, it's possible to deleting the value again, but when nothing char in my value, I can't use backspace anymore sir – ProLuck Apr 29 '21 at 05:18
  • Your code clearly says: check if there's **one** character left then cancel the backspace - `inputVal.substr(0, (inputVal.length - 1))` just remove the substr part. Why's that there if it's not what you want? – freedomn-m Apr 29 '21 at 07:35

1 Answers1

0

The main problem is that your code for checking the length of the field is wrong. You just need to use $(this).val().length:

$("input[name='test']").on({
    keydown: function (event) {
    const selector = event.which;
    
    if (selector == 69) {
        event.preventDefault();
    } else if (selector == 8) {
        const inputVal = $(this).val();
      
        if (inputVal.length == 0) {
            console.log("stop it, it's already empty");
            event.preventDefault();
        }
    }
  }
})

However, even this will fail if the user types something non-numeric into the field, since .val() will return the result cast to a number but that will not necessarily correspond to the actual value.

For example, type "abc" and you will see that this code fails. For more details see Get the value of a input number in jQuery.

kmoser
  • 8,780
  • 3
  • 24
  • 40
  • thanks before sir. when I try with your solution my input value length is return 1 and not become 0, oh ya when I try with non-numeric it doesn't giving me anything error in my console or anything sir....and the result still not right – ProLuck Apr 29 '21 at 04:56
  • @LuckALip What results are you looking for? Please describe exactly how you expect this to operate. – kmoser Apr 29 '21 at 05:47
  • FYI `.val()` will **always return a string** - it does not "cast to a number" - `.data()` does that, not `.val()`. Here's a test you can run - enter `1` in the input and tab out: https://jsfiddle.net/xevhmuyo/ – freedomn-m Apr 29 '21 at 07:31
  • @freedomn-m I hear what you're saying, and normally I would agree with you, but here is a slight variation where the input field is `type="number"`. When you enter a string (e.g. "foo") and tab out, `.val()` returns an empty string: https://jsfiddle.net/62jrhtgw/. How would you explain this behavior? – kmoser Apr 29 '21 at 08:04
  • @kmoser https://jsfiddle.net/a8qL569g/ still gives `==="1"` not `===1` when input type = number. Your fiddle doesn't check if it's a string or number. With input type=number, I can't enter a string (Chrome) - but yes, the value should be `""` when "foo" as the string can't be parsed into a number. But `.val()` is *still* outputting as a `string`. It's likely what you've called "cast to a number" is actually "parse as a number" whereas I've assumed you meant "coerced to a number", which it doesn't do. – freedomn-m Apr 29 '21 at 08:12
  • 1
    @freedomn-m Agreed, "cast to a number" was a poor choice of words on my part. In any case, the whole point of my Fiddle is to show that when you enter non-digits into a `type="number"` input field, the browser gives you back something other than what you entered. I tested with Firefox, not Chrome. – kmoser Apr 30 '21 at 06:32