Can this code be shorten in some way? I've tried several ways to compact it, but I can't get it to work:
//Customer info
$('input#state-field-a, input#state-field-b').hide();
$('select#country-a').change(function(){
if ($(this).val() === "United States" || $(this).val() === "Canada" ||$(this).val() === "null")
{
$('select#state-a').show();
$('input#state-field-a, input#state-field-b').hide();
} else {
$('select#state-a').hide();
$('input#state-field-a').show();
}
});
//Shipping nfo
$('select#country-b').change(function(){
if ($(this).val() === "United States" || $(this).val() === "Canada" ||$(this).val() === "null")
{
$('select#state-b').show();
$('input#state-field-b').hide();
} else {
$('select#state-b').hide();
$('input#state-field-b').show();
}
});
Thanks in advance.
UPDATE: I forgot to give some context to this.
I have two areas in the same page, one for Billing/Customer Info and other for Shipping Info, when the user selects an option from the select menu, other options show/hide within the same section. Both functions should work 'independent' than each other since they belong to different sections.
For example, if I select Canada from the Customer Info select menu, it can't change/alter anything in the Shipping Info section.
Not sure if that makes sense.
Thanks again for any help on this.
You can use a few shortcut functions to narrow all of your code down to this:
$('#state-field-a, #state-field-b').hide();
$('#country-a, #country-b').change(function(){
var m = $.inArray($(this).val(), ["United States","Canada","null"]) != -1;
$('#' + this.id.replace('country', 'state') + '-a').toggle(m);
if(this.id === 'country-a') $('#state-field-b').toggle(m);
$('#' + this.id.replace('country', 'state-field') + '-a').toggle(!m);
});
We're doing a few things different here:
.change() once, since they both have the same effect$.inArray() to narrow down the if or clauses (IE doesn't have .indexOf()...).toggle(bool) instead of repeated .show()/.hide() codeif is to account for the difference in your two handlersIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With