Eleeist
Eleeist

Reputation: 7041

How do I get the selected option in a list?

Let's say I have the following drop down list.

<select id="products">
    <option value="test1">Test1</option>
    <option value="test2">Test2</option>
</select>

I want to show specific div's only when a specific option is selected. I know how to show and hide them, but I have no idea how to detect.

  1. The selected option when the page is loaded, and
  2. The selected option when a user selects something else.

Upvotes: 1

Views: 62

Answers (2)

Avitus
Avitus

Reputation: 15958

  1. On document ready you just do $("#list option:selected").text(); or .val(); depending on what you need.

      $(document).ready(function() {   alert($("#products
      option:selected").text()); });
    
  2. You can either bind a .change function to the list or you can have an onchange function inline in the html.

    $("#products").change(function() {
    alert($("#products
     option:selected").text()); 
    });
    

Upvotes: 2

Ram
Ram

Reputation: 144669

this will get the selected values and store them in an array, last index of array is the newest value and previous values are selected before:

var valArr = [];
$("#products").change(function(){
    valArr.push($(this).val());
})

alert(valArr);

Upvotes: 0

Related Questions