robinhood91
robinhood91

Reputation: 1691

jQuery check what option is selected

If I have this code:

<td class="field-type">                  
     <select id="id_virtual_as_set-0-type" name="virtual_as_set-0-type">
       <option value="M">M</option>
       <option value="AI" selected="selected">AS I</option>
       <option value="D">D</option>
       <option value="P">P</option>
       <option value="A">A</option>
       <option value="R"</option>
     </select>      
</td>

And I wish to find out which option value is selected, how can I do this via jQuery? Also the issue is that I have a handle on the <td> element and I want to be able to access the <select> from the <td> element and then check what the selected option is.

Upvotes: 0

Views: 2143

Answers (3)

jesuisgenial
jesuisgenial

Reputation: 725

There's many way to do it. And this is how I do

$('select').on('click', function() {
    console.log($(this).find('option:selected').val());
});

Upvotes: 0

favirguezc
favirguezc

Reputation: 21

Yes.

Just try:

$("#id_virtual_as_set-0-type").val()

Upvotes: 2

Alen.Toma
Alen.Toma

Reputation: 4870

Here, i have created an example of how to do this.

$(document).ready(function(){
function getSelectedProperty(select){
var selectedOption = select.find("option:selected");
$("p").html("selected Value:"+selectedOption.val() + " SelectedText:" +selectedOption.html())
}
var select = $("select");
select.change(function(){
getSelectedProperty($(this));

});
getSelectedProperty(select);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="field-type">                  
     <select id="id_virtual_as_set-0-type" name="virtual_as_set-0-type">
       <option value="M">M</option>
       <option value="AI" selected="selected">AS I</option>
       <option value="D">D</option>
       <option value="P">P</option>
       <option value="A">A</option>
       <option value="R"</option>
     </select>      
     
     <p></p>
</td>

Upvotes: 0

Related Questions