Mindlogix Technologies

Mindlogix Technologies

How to get HTML SELECT > options using jQuery?

Sometime we need to get the value of html select element using jquery. Many ways are doing this

1 way of achieving this by  using the jQuery :selected selector with the combination of the val() method to find the selected option value in a select box or dropdown list.

  <form>
<label>Select Country:</label>
<select class="country">
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(this).children("option:selected").val();
alert("You have selected the country - " + selectedCountry);
});
});
</script>

Sometime we need to get multiple selected option values of html select element using jquery. This can be achieve like this way,

  <form>
<label>Country:</label>
<select class="country" multiple="multiple" size="5">
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="brazil">Brazil</option>
<option value="germany">Germany</option>
</select>
<a class="clickMe" href="#">Get Values</a>
</form>
<script>
$(document).ready(function() {
$("a.clickMe").click(function(){
var countries = [];
$.each($(".country option:selected"), function(){
countries.push($(this).val());
});
alert("You have selected the country - " + countries.join(", "));
});
});
</script>