cgrouge cgrouge - 1 year ago 61
HTML Question

How to assign value to unchecked checkboxes

I'm creating a form with multiple checkboxes and I want to value of the checked checkboxes to be "yes" and the value of unchecked checkboxes to be "no". The site I'm hosting my form on does not let me add the hidden field with the same name and a different value so I have to find script that will add the hidden checkbox on submission and include the value of "no". Currently, when I submit the form the unchecked boxes are recorded as undefined but for data purposes I need it to be filled with "no".

Here is what I found:

function() {

// Add an event listener on #foo submit action...
// For each unchecked checkbox on the form...

// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "no"); // or 'off', 'false', 'no', whatever

// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;

} // end function inside each()
); // end each() argument list

return true; // Don't abort the form submit

} // end function inside submit()

Why is the script not working?

Answer Source

I was able to use this much simpler script. Works perfectly.

$('#foo').click(function () {
    $(this).find('input[type="checkbox"]').each( function () {
        var checkbox = $(this);
        if(':checked')) {
        } else {
            checkbox.after().append(checkbox.clone().attr({type:'hidden', value:'no'}));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download