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