Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - Hide option from dropdown 2 when selected in dropdown 1

I have two dropdowns, both have the same items in them. If an option is selected in dropdown 1 then I would like to hide that option in dropdown 2. When it is unselected in dropdown 1 I would like it to appear again in dropdown 2 and whichever option is then selected to then be hidden in dropdown 2. I am trying to have this exclude the blank option in the first index.

Here is a codepen that I started, but I am not sure where to go from here:

http://codepen.io/cavanflynn/pen/EjreJK

    var $dropdown1 = $("select[name='dropdown1']");
    var $dropdown2 = $("select[name='dropdown2']");

    $dropdown1.change(function () {
        var selectedItem = $($dropdown1).find("option:selected").val;
});

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As said in comments, one of the options is to disable/enable options according to the selection in the first select, like below. This would work on all browsers as opposed to hide/show which doesn't.

var $dropdown1 = $("select[name='dropdown1']");
var $dropdown2 = $("select[name='dropdown2']");

$dropdown1.change(function() {
    $dropdown2.find('option').prop("disabled", false);
    var selectedItem = $(this).val();
    if (selectedItem) {
        $dropdown2.find('option[value="' + selectedItem + '"]').prop("disabled", true);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="dropdown1">
  <option></option>
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
</select>

<select name="dropdown2">
  <option></option>
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
  <option value="3">Test 3</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...