1

Using jquery, how can I select all elements that dont have attribute's value in a array of values?

Let's say I have the array ['a', 'b'] and inputs

<input value="a">
<input value="b">
<input value="c">
<input value="d">

How can I select only those with values c and d? Is there a way without each() using some kind of selector so I can use it for exampe with find(selector) function?

0

2 Answers 2

6

select all input using $('input') and then use filter()

var arr = ['a', 'b'];

var inputs = $('input').filter((x,y) => !arr.includes($(y).val()));
console.log(inputs.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="a">
<input value="b">
<input value="c">
<input value="d">

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

1 Comment

That great, I didn't got the idea to look for a filter() function or similar. I was only trying to mix up some selector. Thanks!
3

You can use :not() pseudo selector

let not = ['a', 'b'];
$(`input:not([value=${not[0]}],[value=${not[1]}])`).val(1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input value="a">
<input value="b">
<input value="c">
<input value="d">

alternatively

let not = ['a', 'b'];
$(`input:not(${not.map(prop => `[value=${prop}]`)})`).val(1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input value="a">
<input value="b">
<input value="c">
<input value="d">

3 Comments

what if there are too many values in not array , can there be a way around it
@Dij $(`input:not(${not.map(prop => `[value=${prop}]`).join(",")})`);
interesting, what is the purpose of join() in the end.

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.