问题
I have a form (it's a WordPress plugin, Contact 7, fyi) that uses an exclusive checkbox. There are two checkbox choices, yes and no. If they check yes, I have a text field that I am enabling (I have disabled it by default). If they check no, I have a second exclusive checkbox with 2 boxes that I am enabling (also by default). As you can surmise, when the user selects yes, it also should disable the second checkbox. And if they choose no, I want the text field to return to disabled state.
So I have this working, except, it doesn't recognize the change event; in other words, if I check yes, it enables the text field, but if I then check no, it does not update the associated states of the other input elements. I have to uncheck the no, then recheck it, in order for it to perform the function. Here is my jQuery code snippet:
$(document).ready(function() {
$('p#myTextFieldHolder input:text').val('').attr('disabled', true);
$('#mySecondCheckBoxHolder input:checkbox').attr('disabled', true);
$("#myCheckBoxHolder input").change(function() {
if ($(":checked").val() == "If yes, what is the estimated closing date?") {
$('p#myTextFieldHolder input:text').val('').attr('disabled', false);
$('#mySecondCheckBoxHolder input:checkbox').attr('disabled', true);
} else if ($(":checked").val() == "No:") {
$('p#myTextFieldHolder input:text').val('').attr('disabled', true);
$('#mySecondCheckBoxHolder input:checkbox').attr('disabled', false);
} else {
$('p#myTextFieldHolder input:text').val('').attr('disabled', true);
$('#mySecondCheckBoxHolder input:checkbox').attr('disabled', true);
}
})
});
Any suggestions on how to account for this and correct it? Thank you.
回答1:
Here is an example of what you asked for, hope it helps
$(function(){
$('#chkboxes input:checkbox').on('change', function(){
if($(this).is(':checked'))
{
if($(this).attr('id')=='yes')
{
$('#txt1').prop('disabled', false);
$('#chkno input:checkbox').prop('disabled', true).prop('checked', false);
$('#no').prop('checked', false);
}
else
{
$('#txt1').val('').prop('disabled', true);
$('#chkno input:checkbox').prop('disabled', false);
$('#yes').prop('checked', false);
}
}
});
});
来源:https://stackoverflow.com/questions/12322630/jquery-checkbox-disable-enable-secondary-inputs-based-on-checkbox-value