JavaScript Validation For Checkbox, When Multiple checkbox selected from option list

18,919

If you want to get the list of selected checkbox values.. you can use this..

$('#someButton').click(function() {
    var values= [];
    $('#MyDiv input:checked').each(function() {
        values.push(this.val);
    });
    // now values contains all of the values of checked checkboxes
    // do something with it
});
Share:
18,919
Rahul Barge
Author by

Rahul Barge

Updated on June 04, 2022

Comments

  • Rahul Barge
    Rahul Barge almost 2 years

    I want to do JavaScript validation for Checkbox

    If Value from Checkbox is not selected, it should get alert "Please Select Languages You Know"

    But if user select 2 Languages from list of checkbox. I need that 2 languages should get alert using JavaScript.

    I know to do with single checkbox, but not getting how to do using array.

    Here is my Code...

    <script type="text/javascript">
     
    function myFunction(form){
        
      var i,
      chks = document.getElementsByName('lang[]');
      
      for (i = 0; i < chks.length; i++){
        if (chks[i].checked){
            
          //Here how i should alert selected values 
            
            return true;
        }else{
            alert('No item selected');
            return false;
        }
      }
    }
    </script>
     <form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
    
          <div id="languageId"><label>Language : </label>
                                                            
              <input type="checkbox" name="lang[]" value="english" >English</input>
                                            
              <input type="checkbox" name="lang[]" value="marathi">Marathi</input>   
    
               <input type="checkbox" name="lang[]" value="hindi">Hindi</input> 
                                                        
          </div>
    
         <div id="submit1"><button type="submit">Submit</button></div><br/>
    
         </form>

    Thank You, Rahul

  • KooiInc
    KooiInc over 9 years
    I didn't notice a jquery tag in the question.