Reputation: 1143
I'm trying to validate input using JavaScript, what i want is to bring up an alert if the user enters something that is not included in my array.
Here is what i have so far
var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"];
//dont mind the i it's been previously declared
val =+ document.getElementById('arrow_' + i + '_1').value
alert(val);
alert(validAr.indexOf(val));
If for example in the above the user enters '5' I'll alert '5', the value of val
and then -1 which means that it does not belong to the array. How do I solve this?
Upvotes: 0
Views: 117
Reputation: 3362
As you are using jQuery you can do:
if (jQuery.inArray(val,validAr)==-1)
{
alert('Invalid');
}
Upvotes: 0
Reputation: 25527
try
$(document).ready(function () {
var validAr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "m", "M"];
$("#text").change(function () {
if (jQuery.inArray($(this).val(), validAr) == -1) {
alert("exception");
}
});
});
<input type="text" id="text" />
Upvotes: 0
Reputation: 10896
just convert your value in string
alert(validAr.indexOf(val.toString()));
and also remove + from +document.getElementById('arrow_'+i+'_1').value
so your code will be
var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"];
//dont mind the i it's from a for above
val = document.getElementById('arrow_'+i+'_1').value;
alert(val);
alert(validAr.indexOf(val.toString()));
Upvotes: 1
Reputation: 165951
Your array contains strings but you're converting the value to a number:
val = +document.getElementById('arrow_'+i+'_1').value
// ^ Remove this to keep the value as a string
Since Array.prototype.indexOf
performs a strict equality comparison it fails to find the value in the array.
You could replace the values of your array with actual numbers, but since "m"
and "M"
will not convert to numbers it won't work that way (you'll end up with NaN
when you try to coerce them).
Upvotes: 3