简体   繁体   中英

Showing and hiding select boxes using javascript/

I have a little bit of test code that intends to have a select box display when a certain option is selected and then hide when that option is changed.

HTML:

<form>
    <select id="sel1" name="sel1" class="chzn-select">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    <select id="sel2" name="sel2" selected="selected" style="display:none">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

JS:

var selCategory = $('#sel1');
$(selCategory).change(function () {
  $('option:selected').each(function () {
    if ($(this).text() ==='2') {
      $('#sel2').show();
    }
    else if($(this).text() ==='1') {
      $('#sel2').hide();
    }
    else if($(this).text() ==='3') {
      $('#sel2').hide();
    }
  });
});

This bit of code works great if only this:

if ($(this).text() ==='2') {
  $('#sel2').show();
}

Is the JavaScript but falls down when adding the else if statements. Also would it be better to display the select box itself or a containing div Tag? The only reason the second select box isn't a chosen-select is that chosen doesn't seem to like elements that are already hidden (problems with width).

Any help would be appreciated.

I would make it easier, grab the value and concatenate the sel ID from that:

$("#sel1").change(function() {
    $("select:not(#sel1)").hide(); //hide other selects, excluding #sel1
    $("#sel" + this.value).show();
});

Your $('option:selected') selector is looking at the options from all select elements, not just #sel1 . So #sel2 is shown (due to "2" selected in the #sel1 ), then immediately hidden (due to "1" selected in #sel2 itself). Make sure you're looking only at the value you want:

var selCategory = $('#sel1');

selCategory.change(function () {
  selCategory.find('option:selected').each(function () {
    if ($(this).text() =='2') {
      $('#sel2').show();
    }
    else {
      $('#sel2').hide();
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM