Latox
Latox

Reputation: 4705

jquery change/toggle?

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
Options change depending on if A or B is chosen

How can we accomplish this?

Upvotes: 2

Views: 1561

Answers (3)

Kokos
Kokos

Reputation: 9121

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.

Upvotes: 1

miku
miku

Reputation: 188224

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

Upvotes: 0

minikomi
minikomi

Reputation: 8503

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');

Upvotes: 0

Related Questions