Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: shorten code

Tags:

jquery

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.

like image 488
Ricardo Zea Avatar asked Apr 09 '26 17:04

Ricardo Zea


1 Answers

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:

  • Not using tag selectors on IDs
  • Using .change() once, since they both have the same effect
  • Using $.inArray() to narrow down the if or clauses (IE doesn't have .indexOf()...)
  • Use .toggle(bool) instead of repeated .show()/.hide() code
  • The extra if is to account for the difference in your two handlers
like image 120
Nick Craver Avatar answered Apr 12 '26 06:04

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!