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?
asked Sep 19, 2017 at 1:07
2 Answers 2
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">
answered Sep 19, 2017 at 1:12
1 Comment
simPod
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!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
Dij
what if there are too many values in
not
array , can there be a way around itguest271314
@Dij
$(`input:not(${not.map(prop => `[value=${prop}]`).join(",")})`);
Dij
interesting, what is the purpose of join() in the end.
lang-js