开发者

jquery change/toggle?

开发者 https://www.devze.com 2023-03-12 18:22 出处:网络
We want to create a form which when an option is chosen in a select box, the options change in the other select box, depending on which is selected.

We want to create a form which when an option is chosen in a select box, the options change in the other select box, depending on which is selected.

Example:

Select box 1
Option A
Option B

Select box 2
Option开发者_开发问答s change depending on if A or B is chosen

How can we accomplish this?


There are a couple of ways, the specifics depend on if you want the options from the second select box to be called through Ajax or if there's a set two possibilities.

HTML

<select id="select1">
    <option value="a">a</option>
    <option value="b">b</option>
</select>

<select id="select2a" style="display:none;">
    <!-- options -->
</select>

<select id="select2b" style="display:none;">
    <!-- options -->
</select>

jQuery

$('#select1').change(function(){

    if($(this).val() == "a"){

        $('#select2a').show();
        $('#select2b').hide();      

    }elseif($(this).val() == "b"){

        $('#select2a').hide();
        $('#select2b').show();  

    }

});

If you don't want to use two seperate selectboxes, you could store the options within a variable and change the .html() of the selectbox depending on the option chosen in the first selectbox.


From the jQuery docs:

http://api.jquery.com/selected-selector/

$("select").change(function () {
      var str = "";
      //example from the docs - put code here which is specific to your use case.
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .trigger('change');


Here is a short blog entry describing and implementing some conditional logic with select input and jQuery:

  • Select Menus and Conditional Logic with jQuery
0

精彩评论

暂无评论...
验证码 换一张
取 消