Reputation: 107
My question is the following.
I will provide a simplified code to illustrate my problem:
html:
<form>
<input type="number" id="someNumber">
<input type="button" id="submitBtn">
</form>
jquery:
$("#submitBtn").click(function() {
var numberValue = $("#someNumber").val();
if(numberValue.trim() == "") {
$("#someNumber").attr("class", "inputError");
}
});
css:
.inputError {
border: 1px red solid;
}
Now, my problem is that, even when the value on the input is "asd", jquery takes that as an error and numberValue.trim() == ""
is true. The only way that it returns false is if the input value is a number. That should however, with the code I wrote, not be the case, right? I just want to check wether or not the input field is empty.
Upvotes: 1
Views: 783
Reputation: 100195
as the input type number expects number only, when you enter string it changes to empty, so either change your input type number to text in order to check for emptiness, else validate your input type number.
$("#submitBtn").click(function() {
var numberValue = $("#someNumber").val();
if( !$.isNumeric(numberValue) ) {
$("#someNumber").attr("class", "inputError");
}
});
Upvotes: 0
Reputation: 56
Here you got bitten by the HTML5-Snake :) You are right that the JS returns and empty result for non numbers which is expected behaviour.
To read further about that here a link to w3c
http://www.w3.org/TR/html5/forms.html#number-state-(type=number)
Upvotes: 2
Reputation:
If you want the user to enter text, use
<input type = "text">
Input type number takes any text as "", and hence you are getting true for it
Upvotes: 2