# Options with a “yes” or “no” radio button

I have about 6 of these, but I'm only posting two. Essentially I have a bunch of options with a "yes" or "no" radio button. If "no" is selected, I want a form to popup.

$('#Option1').live('change', function() { if ($('input[name=Option1]:checked').val() == "False") {
$('#formDiv').show(); } else {$('#formDiv').hide();
}
});
$('#Option2').live('change', function() { if ($('input[name=Option2]:checked').val() == "False") {
$('#formDiv').show(); } else {$('#formDiv').hide();
}
});


How can I make this more efficient, or even consolidate it? Or is having a function for each pair of radio buttons necessary?

This should work:

$('#Option1, #Option2').live('change', function() { if ($('input[name=' + $(this).attr('id') + ']:checked').val() == 'False') {$('#formDiv').show();
else {
$('#formDiv').hide(); } });  Or, if whatever has the id option1 is the same page element as the input with the name option1, you could do: $('#Option1, #Option2').live('change', function() {
if ($(this).val() == 'False')$('#formDiv').show();
else {
$('#formDiv').hide(); } });  • .show and .hide could be replaced to a .toggle($(this).val()=='False') statement. – biziclop Jan 17 '12 at 14:29

I'd recommend setting up a listener on all your radio buttons then using 'this' to reference the radio button that is selected. If you are writing six identical functions, you're not adhering to DRY.

Without the HTML to back this up, it's a little tricky to see exactly what's going on.

You could bind the selection change to a class instead of the id, this way you will have a generic function valid for all the select elements. Something like :

$('.mySelect').live('change', function() { var selectedOptionValue =$(this).val();
if ($('input[name='+selectedOptionValue+']:checked').val() == "False") {$('#formDiv').show();
}
else {
\$('#formDiv').hide();
}

});