How to add jQuery validation to SumoSelect drop downs?

1k Views Asked by At

I am looking for a way to validate multiple sumo select boxes. The code I have is as follows.

HTML

<select class="kid-age form-select" id="edit-age-big-kid-1" name="age_big_kid_1">     
    <option value="">-</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
</select>

<select class="kid-age form-select" id="edit-age-big-kid-2" name="age_big_kid_2">     
    <option value="">-</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
</select>

<select class="kid-age form-select" id="edit-age-small-kid-1" name="age_small_kid_1">     
    <option value="">-</option>
    <option value="3">0</option>
    <option value="4">1</option>
    <option value="5">2</option>
</select>

JS

$('.kid-age').SumoSelect();

How can I client side validate all of the drop downs (there may be multiple) to be required and display a single message "All kid ages are required."

Thanks in advance!

1

There are 1 best solutions below

5
On BEST ANSWER

Here is quick and simple validation, but it will give you idea, you can modify it to fit your needs:

$(document).ready(function () {

   $('.kid-age').SumoSelect();
   $('#submit').on('click', function() {
       errors=[];
       $('p.SelectBox').each(function() {

          if($(this).attr('title')==" -") {



              errors.push('invalid');

          }

       });

        if(errors.length>0) { // if there are errors, show message, stop submission, etc...
               message='All kid ages are required.';
               $('.error').text(message);
          }
          else { //if no errors, continue with script execution...
              $('.error').text('fields validated');
          }
   });


});

Plugin creates one specific p tag (for all dropdowns) which holds selected options... so, you can check its value, and if different than ' -', continue script execution, otherwise error will be thrown.

See it in action: https://jsfiddle.net/g7bLbevy/