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

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

Answers


$("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.


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


this will work

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

        return false;
    });
});

var inputElements = document.getElementsByClassName('messageCheckbox');
    var checkedValue=[];
    for(var i=0; inputElements[i]; ++i){
       console.log(inputElements[i]);
       if(inputElements[i].checked){
           checkedValue.push(inputElements[i].value);
       }
    }
alert(checkedValue)

Need Your Help

Create and "Save As" text file automatically using PHP

php text-files

So, I am trying to export some data from a database and have it automatically prompt the user to save the data has a text file. Here is my code:

Ajax seo techniques

php javascript html ajax seo

I've read some topics regarding enabling google to crawl ajax based sites but the information is quite controvesrial. Is it possible? If yes can someone post a link to a tutorial please?