Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checked checkbox values in an array on form submit

Tags:

html

jquery

I want to get all the values of checkboxes and alert them that are checked on form submit,

Here is what I have tried so far:

HTML

<form id="calform">
<input type="checkbox" value="one_name" />
<input type="checkbox" value="one_name1"/>
<input type="checkbox" value="one_name2"/>
<input type="submit" value="Submit" />
</form>

jQuery Script

      $("#calform").submit(function(e){

    // array that will store all the values for checked ones
    var allVals = [];

    $('input[type="checkbox"] :checked').each(function() {

    // looping through each checkbox and storing values in array for checked ones.
    allVals.push($(this).val());

    });

    alert(allVals);

    e.preventDefault();
    });

Here it is on JSFIDDLE

Alert box shows up empty on form submit.

like image 610
Jade Avatar asked Jan 28 '14 05:01

Jade


1 Answers

Use $('input[type="checkbox"]:checked'), note the space was removed between input[type="checkbox"] and the pseudo class :checked:

UPDATED EXAMPLE HERE

 $("#calform").submit(function (e) {

     var allVals = [];

     $('input[type="checkbox"]:checked').each(function () {
      //     removed the space ^

         allVals.push($(this).val());
     });
     alert(allVals);

     e.preventDefault();
 });
like image 82
Josh Crozier Avatar answered Oct 31 '22 15:10

Josh Crozier