lundi 27 juillet 2015

if/switch statement based on a select value and array?

I have a simple select element with multiple values which basically group in to four categories. To try and be more efficient I thought it would be best to group them in to arrays and check if the "selected" value is in one of them, printing different text based on which arrays the select value is in. Also wouldn’t be more efficient to do it with a switch?

$("#search2")
  .change2(function() {
    var group1 = ['IA', 'KS'];
    var group2 = ['MN', 'OK'];
    var group2 = ['KE'];
    var optionValue = "";
    $("#search2 option:selected").each(function() {
      optionValue += $(this).val() + " ";
    });
    if ($.inArray(optionValue, group1)) {
      $(".result2").text("element in group 1");
    } else if ($.inArray(optionValue, group2)) {
      $(".result2").text("element in group 2");
    } else if ($.inArray(optionValue, group3)) {
      $(".result2").text("element in group 3");
    } else {
      $(".result2").text("element in group 4");
    }
  })
  .trigger("change2");

Aucun commentaire:

Enregistrer un commentaire