简体   繁体   中英

Jquery select option val

im working in a project that i will have about 10 select boxes with same class and i want to check if ALL of selected boxes are selected with jquery. Here is my html code

<form class="form-horizontal" action="analysis.php" method="post" id="mobileform" >
<select class="form-control selectx" name="phone1">
    <option value="" selected>Select phone</option>
    <option value="iphone6" selected>Iphone 6</option>
    <option value="galaxys5" selected>Galaxy S5</option>
</select>            
<select class="form-control selectx" name="phone2">
    <option value="" selected>Select phone</option>
    <option value="iphone6" selected>Iphone 6</option>
    <option value="galaxys5" selected>Galaxy S5</option>
</select>       
<button type="submit" name="submit" class="btn btn-success" id="submit"> Submit !</button><br>   

And here is my jquery

                            $(document).ready(function() {
                            $('form').submit(function(event) {
                                $(".selectx option:selected").each(function()
                                {
                                    if($(this).val() === "") {
                                    $('#selecterror').fadeIn(300);
                                    event.preventDefault();
                                }else{
                                    $('#selecterror').hide();
                                    }
                                });
                              });
                        });

But it doesnt work if you example in 1st selectbox with name phone1 you dont select anything and in selectbox with name phone2 you select a phone.

Sorry for my english

In your case, both select options have to be empty for the validation. You can use .filter to see if any of the select options is empty:

 $('form').submit(function(event) {
      var empty = $(".selectx option:selected").filter(
            function() {
                return $(this).val() == "";
             });

      if(empty.length) {
              $('#selecterror').fadeIn(300);
              event.preventDefault();
      }else{
              $('#selecterror').hide();
      }

  });

DEMO: https://jsfiddle.net/hptqq1tL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM