2

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

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

this will work

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

        return false;
    });
});

1 Comment

It would be good if you could add some explanation of the code - it might be more helpful for other users.
-1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.