Changing functions based on checkbox being checked or not
I have the same function checking 2 different text input fields in a form. If a checkbox is checked, I need the function to run on one of the text input fields. If the checkbox is not checked, I need the function to run on the other text input field.
Here is the checkbox:
<input id="use_different_addresses" type="checkbox" value="1" name="use_different_addresses" />Use different address<br />
By default the checkbox is not checked. When unchecked, I need this function to run:
$('#customer_country_name').change(function() {
if ($('#customer_country_name').val() != 'United States') {
$('.radio_us').hide();
}
else {
$('.radio_us').show();
开发者_Go百科 }
});
When the checkbox is checked, I need this function to run:
$('#shipping_country_name').change(function() {
if ($('#customer_country_name').val() != 'United States') {
$('.radio_us').hide();
}
else {
$('.radio_us').show();
}
});
Thanks!
Why not just add a check to the top of each method to determine if it should run or not based on the checked
state
$('#customer_country_name').change(function() {
if (!$('#use_different_addresses').is(':checked')) {
...
}
}
$('#shipping_country_name').change(function() {
if ($('#use_different_addresses').is(':checked')) {
...
}
}
EDIT
OP clarified in comments that they wanted certain radio boxes to be hidden when the check-box was checked. Here's the solution I recomended
$('#use_different_addresses').change(function() {
if ($('#use_different_addresses').is(':checked')) {
$('.radio_us').hide();
} else {
$('.radio_us').show();
}
});
Without seeing more markup, you can use .toggle()
to trigger the .change()
$("#use_different_addresses").toggle(function(){
$('#customer_country_name').change();
}, function(){
$('#shipping_country_name').change();
});
Finally got it to work here:
http://jsfiddle.net/4UkTP/
It's probably not the prettiest jQuery (I'll admit I'm a newbie), but it works! :)
精彩评论