问题
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
回答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.
回答2:
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
回答3:
this will work
$(function() {
$("#frm1").submit(function() {
$("input.test[type=checkbox]:checked").each(function() {
alert($(this).val());
});
return false;
});
});
回答4:
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)
来源:https://stackoverflow.com/questions/11515743/get-checkbox-value-on-form-submit-and-store-in-a-variable-using-jquery