TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

jQuery validate multiple select options per page

I have many select boxes on a page form. I am trying to find a way to check all the select options rather than doing if/else for each one.

So far I have tried !== and != and empty

<select name="fruits" id="fruits">
    <option value="0">-- Choose --</option>
    <option value="1">Apple</option>
    <option value="2">Orange</option>
</select>

<select name="cakes" id="cakes">
    <option value="0">-- Choose --</option>
    <option value="1">Chocolate</option>
    <option value="2">Strawberry</option>
</select>

<select name="breads" id="breads">
    <option value="0">-- Choose --</option>
    <option value="1">Garlic Bread</option>
    <option value="2">Baker Loaf</option>
</select>

My JavaScript (jQuery)

function checkEmpty(){
    var flag = 0;

    if(
        $('select').val()!=="" ||
        $('select').val()!=="-- Choose --" ||
        $('select').val()!=="0"){
            flag=1;
            $('select').addClass('error');
    } else {
            $('select').removeClass('error');
    }

    if(flag==1){
        alert('One or all options must be selected!');
    } else {
        console.log('The user made a selection');
    }

}

The user needs to choose one of the select boxes or all of them. One must at least be chosen.

Upvotes: 0

Views: 84

Answers (2)

Ulrich
Ulrich

Reputation: 1

This should work for you:

function checkEmpty(){
  var checked = 0;
  $('select').each(function(){
    if($(this).val()!=="0")
    checked++;
  });
  if(checked===3||checked===1){
    //your code
  }
}

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

You can do it by using filter(),

var selects = $("select");
var selected = selects.filter(function(){ return this.value !== "0" });
var res = selects.length - selected.length
if(res == selects.length - 1 || res == 0){
  console.log('The user made a selection');
} else {
  console.log('One or all options must be selected!');
}

DEMO

Upvotes: 2

Related Questions