How to use jQuery to grab checkbox values and put them in another form field
I have a form that contains a set of checkboxes. Before submitting the form, I would like to get the checkbox values and paste them into the textbox and then submit that.
So, I could: Red Orange X Yellow Blue X Green
And I would like my textbox to get the content "Yellow, Green".
It doesn't seem too difficult, but I'm completely out of my league. I'm already using jQuery for a few other things, so I have a ready-made environment if that makes it easier.
Thanks for any advice -
Just use this code:
$(function(){
$('#YourFormID').bind('submit',function(){
var serializedCheckboxes = '';
$("input[type=checkbox]").each(function() {
if($(this).attr("checked")) {
serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value");
}
});
$("input[name=allchecks]").attr("value", serializedCheckboxes);
});
});
It runs when the page is loaded and binds to the submit event of your correct form function.
source to share
fix Josh code:
var serializedCheckboxes = '';
$("input[type=checkbox]").each(function() {
if($(this).attr("checked")) {
serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value");
}
});
$("input[name=allchecks]").attr("value", serializedCheckboxes);
After my fix, you shouldn't get additional "," after the last option.
source to share
So, more improvements. Add the class name (in my example "colorCheckBoxes") to all the checkboxes with colors in your form (if checked) - this help avoids problems when you want to use different additional checkboxes in your form for other purposes than choosing colors. Then use this code:
$(function(){
$('#YourFormID').bind('submit',function(){
var serializedCheckboxes = '';
$(this).find("input[type=checkbox]").filter('.colorCheckBoxes').each(function() {
if($(this).attr("checked")) {
serializedCheckboxes += (serializedCheckboxes != '' ? ', ' : '') + $(this).attr("value");
}
});
if (serializedCheckboxes != '')
$(this).find("input[name=allchecks]").attr("value", serializedCheckboxes);
});
});
source to share