-1

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'?

3
  • What have you tried? Commented Jul 27, 2016 at 11:26
  • var exists = selected_options.indexOf('CancelTerms') > -1 Commented Jul 27, 2016 at 11:27
  • $('input[checked=checked][name="CancelTerms"]') .length > 0 Commented Jul 27, 2016 at 11:29

2 Answers 2

0

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
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer really appreciate. I have three values to check how can I do that ?
@user4676307: inside bot , seperate :not([name="CancelTerms"],[.....],[......])
@user4676307 some(function(v){ return ["CancelTerms", "namme1","name2"].indexOf(v) >-1 ; })
@user4676307 : glad to help you :)
0

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

@eisbehr: same thing. str1 exists.

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.