Get checkbox value on form submit and store in a variable using jQuery

15,349

Solution 1

$("form").submit(function() {
    var aVariable = $('input.test[type="checkbox"]:checked', this).val();
});

.val() returns undefined if called on an empty jQuery object, which would be the case here if no checkboxes are checked.

Solution 2

this will work

$(function() {
    $("#frm1").submit(function() {
        $("input.test[type=checkbox]:checked").each(function() {
            alert($(this).val());
        });

        return false;
    });
});

Solution 3

Please try below solution on codebins:

Note: Add latest jquery.js javascript file on header tag first.

HTML:

<form id="frm1" method="post">
  <input type="radio" class="test" checked="checked" value="radio1">
  Radio1
  <input type="radio" class="test" checked="checked" value="radio2">
  Radio2
  <input type="radio" class="test" value="radio3">
  Radio3
  <br/>
  <input type="checkbox" class="test" checked="checked" value="check1">
  Check1
  <input type="checkbox" class="test" value="check2">
  Check2
  <input type="checkbox" class="test" checked="checked" value="check3">
  Check3
  <br/>
  <input type="submit" value="submit" />
</form>

jQuery within Script tag:

$(function() {

    $("#frm1").submit(function() {
        $("input.test[type=checkbox]:checked").each(function() {
            alert($(this).val());
        });

        return false;
    });
});

I have done above bin on http://codebins.com/bin/4ldqpap

Share:
15,349
Chris
Author by

Chris

Updated on June 05, 2022

Comments

  • Chris
    Chris almost 2 years

    Have a form using multiple checkboxes with a class of 'test' (only one of which can be checked however similar to using radio buttons - not my idea btw!).

    When the form is submitted I want to get the value of the checkbox that is checked and store it in a variable - can anyone help here?

    Cheers!

    Chris

  • Roger Rowland
    Roger Rowland about 11 years
    It would be good if you could add some explanation of the code - it might be more helpful for other users.