Set a checkbox to unchecked if a Checkbox or Radio button isn't checked, when specifying by name and value
I need to set a checkbox to be either checked or unchecked based on whether specific
Checkboxes or Radio button are selected.
I know how how to do this for checkboxes when I specify an id # for each element and use
if ($(this).attr('checked')
, but I can't get it to uncheck when I specify the names and values of the checkboxes
instead
.
I also haven't been able to
get it to uncheck when a radio button is unchecked,
even when I specify an id # for each element and use if ($(this).attr('checked'). Ideally, I'd like to
specify the names and values of the
radio buttons instead of using
($(this).attr('checked'), but help with either method (or another one if there's a better way to go) would be appreciated. I also included below a switch function which I'm using for Select elements, but which I've been successful at modifying to use with checkboxes or radio buttons.
I created a working fiddle of this at http://jsfiddle.net/Cfcq6/116/
Checkbox Code 2 - This code both Checks & Unchecks the element
- $('#complaint1').change(function() {
if ($(this).attr('checked')) {
$('input[name="modify_increase"]')[0].checked = true;
}
else {
$('input[name="modify_increase"]')[0].checked = false;
}
});
Checkbox Code 2 - These Check but don't uncheck the element when unselected
- $('.complaint2').change(function() {
if ($('input:checkbox[name=complaint2]:checked').val("Too_small")) {
$('input[name="modify_increase"]')[0].checked = true;
}
else {
$('input[name="modify_increase"]')[0].checked = false;
}
});
Radio Button - These check but don't uncheck the element when unselected
- $('#complaint3').change(function() {
if ($(this).attr('checked')) {
$('input[name="modify_increase"]')[0].checked = true;
}
else {
$('input[name="modify_increase"]')[0].checked = false;
}
});
Switch function which works for Select Elements
- $('.complaint1').change(function () {
$('input[name="modify_increase"]').removeAttr("checked");
$('input[name="modify_decrease"]').removeAttr("checked");
switch($('[name=complaint1]').val()){
case "Too_small":
$('input[name="modify_increase"]')[0].checked = true;
break;
case "Too_big":
$('input[name="modify_decrease"]')[0].checked = true;
break;
}
});