Reputation: 15293
In my form i should apply two variety's of class based on the existence in array for that how do i filter?
this is my try:
<form>
<input type="checkbox" value="one" />
<input type="checkbox" value="two" />
<input type="checkbox" value="three" />
<input type="checkbox" value="four" />
<input type="checkbox" value="five" />
</form>
var names = ["one","two","three"];
$(":checkbox", "form").filter(function(){
return $(this).val() === names
}).addClass("blue")
$(":checkbox", "form").filter(function(){
return $(this).val() !== names
}).addClass("green")
but not works.. any correct way to get it done
Upvotes: 2
Views: 3299
Reputation: 388316
You need to check whether the input value exists in the array, not array names is equal to the value. For that you can use $.inArray, it will return the index of the item if it finds it in the array else -1
$("form :checkbox").filter(function(){
return $.inArray(this.value, names) > -1
}).addClass("blue")
$("form :checkbox").filter(function(){
return $.inArray(this.value, names) == -1
}).addClass("green")
Demo: Fiddle
Or
var names = ["one","two","three"];
$("form :checkbox").addClass(function(){
return $.inArray(this.value, names) > -1 ? 'blue' : 'green'
})
Demo: Fiddle
Upvotes: 4