Reputation: 55865
I am creating a form for a mobile web app with input boxes asking for number input, so I'm using input type="number"
for the validation and it's working well. I am also changing behavior based on the input in the box. I need to hide a div
until the user enters text in the box. When they delete all text from the box, then hide the div
again. This is easy to do - detect keyup
on the input and if its value
is an empty string or not. The problem comes when the user enters text that's not a valid number (possible, at least with iOS keyboard). The value
of the input box is an empty string when the entered text is not a valid number, unfortunately. So my code is hiding the div
when I do still need it to be visible, because it thinks the input box has no value
in it.
How can I get the actual value
stored in a number input type so I can test against it? (I need to keep it a number input type so the proper keyboard appears.) Thanks!
Here's my snippet of code:
$('input.deletable').keyup(function() {
console.log($(document.activeElement).val()); //returns empty string if input is "?)&" for example
if ($(document.activeElement).val() != '')
$('#myDiv').css('display', 'block');
else
$('#myDiv').css('display', 'none');
});
Upvotes: 0
Views: 155
Reputation: 41
I think that "document.activeElement" isnt the best way to get the current input value. You can verify the input validity as well.
$('input.deletable').keyup(function() {
var $this = $(this);
if ($this.val() != '' && this.checkValidity())
$('#myDiv').css('display', 'block');
else
$('#myDiv').css('display', 'none');
});
Upvotes: 1