Input box key Up Check (Validation)
my array
var foo = {};
foo['xarr'] = [ "23" ];
foo['yarr'] = [ "21","21","22","23","24"];
foo['zarr']= [ "70","71","72","73","74","75" ];
Input box takes maximum 4 character and i have a array object i want when a user enter first tow character and it matches from the array i want to add a class on a div. if it matches from foo['xarr'] add some diffrent class,when it matches from foo['yarr'] add some diffrent class and so on.
my html markup:
<li class="Images">
<div>
<input type="text" name="cnumber1" class="inputBx" style="width:58px;" maxlength="4" size="4"/>
</div>
<span class="test"></span>
</li>
Java Script
I was trying through this way but didnt get any success
$('.inputBx').keydown(function() {
var inputVal = $(this).val(),
iLen = inputVal.length;
if( iLen >= 2){
for(var key in foo) {
if( foo[key].indexOf(inputVal) >= 0){
if(foo[key] == 'xarr' )
$('.Images .test ').addClass('fullOpactiy');
if(开发者_开发技巧foo[key] == 'yarr' )
$('.cardImages .test ').addClass('fullOpactiy');
if(foo[key] == 'zarr' )
$('.Images .test ').addClass('fullOpactiy');
}
}
}
});
Something I don't understand in your code :
for(var key in foo) {
if( foo[key].indexOf(inputVal) >= 0){
if(foo[key] == 'xarr' ){
//...
}
}
}
key is in foo object, so it's either xarr, yarr or zarr. Then foo[key] is a number array (which makes correct your sentence foo[key].indexOf(inputVal) >= 0
). Why foo[key]
would ever be equals to the string 'xarr', or 'yarr'?
I suggest this correction before continuing your research :
for(var key in foo) {
var idx = foo[key].indexOf(inputVal); //search in the array
if( idx >= 0){
if(key == 'yarr'){
$('.cardImages .test ').addClass('fullOpactiy');
}
else{
$('.Images .test ').addClass('fullOpacity');
}
return true;//ends your search now, no need to continue
}
}
I think this matching algorithm is suboptimal, but it should work
cheers
Grooveek
this works for me here is aworking demo
var foo = [];
foo['xarr'] = ["23"];
foo['yarr'] = ["21", "21", "22", "23", "24"];
foo['zarr'] = ["70", "71", "72", "73", "74", "75"];
$('.inputBx').keyup(function() {
var inputVal = this.value;
iLen = inputVal.length;
if (iLen >= 2) {
if ($.inArray(inputVal, foo['xarr']) >= 0) {
$('.Images, .test').addClass('fullOpactiy')
}
if ($.inArray(inputVal, foo['yarr']) >= 0) {
$('.cardImages, .test').addClass('fullOpactiy')
}
if ($.inArray(inputVal, foo['zarr']) >=0) {
$('.Images, .test').addClass('fullOpactiy')
}
}
});
精彩评论