I have an array that all the name of all selected check boxes. How can I check if that array contains specific value other than given string.
var selected_options = $('input[checked=checked]').map( function() {
return $(this).attr('name');
}).get();
How can I check if the array selected_options has other elements other than lets say 'CancelTerms'?
2 Answers 2
I don't think there is the need to create an array for that. Just filter out element not having a certain name value using attribute equals selector with :not() pseudo-class selector ( or not() method ) and get its length.
if($('input[checked=checked]:not([name="CancelTerms"])') .length > 0){
// code
}
If you would like to do it with the array then use Array#some method.
if(selected_options.some(function(v){ return v != "CancelTerms"; })){
// code
}
or Array#filter method can be used.
if(selected_options.filter(function(v){ return v!= "CancelTerms"; }).legth){
// code
}
4 Comments
, seperate :not([name="CancelTerms"],[.....],[......])some(function(v){ return ["CancelTerms", "namme1","name2"].indexOf(v) >-1 ; })You can check for the length of array excluding specificvalues occurence count in it:
var selectedcount = selected_options.reduce(function(n, "CancelTerms") {
return n + (val === search);
}, 0);
if(selected_options.length - selectedcount > 0){
//other elements exists
}
Working Snippet:
var selected_options = ["str1","CancelTerms"];
var selectedcount = selected_options.indexOf('CancelTerms') > -1 ? 1 : 0;
if(selected_options.length - selectedcount > 0){
console.log("other elements exists")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
1 Comment
str1 exists.
var exists = selected_options.indexOf('CancelTerms') > -1$('input[checked=checked][name="CancelTerms"]') .length > 0