2

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

here is the fiddle

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

didn't downvote, but why not use names.indexOf(this.value)?
@JanDvorak support for IE < 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.