Reputation: 989
Let's say I have a select options field like so:
<select id="options">
<option value=1>1</option>
<option value=2>2</option>
</select>
How can I check the value of the selected option?
$("#options").value()
returns a TypeError. $("#options").text()
returns ""
and $("#options").val()
returns undefined
.
How can I check the selected integer value?
Upvotes: 0
Views: 3285
Reputation: 732
You will need to add the 'selected' pseudo selector on your div to specify that you want the selected option if you are looking to get the text within the selected div.
So to get the selected text would be:
$( "#options option:selected" ).text();
or if you want to get the value just use:
$( "#myselect" ).val();
You can see more info here in the jquery docs:
Upvotes: 0
Reputation: 1983
$( document ).ready(function() {
var value = $('#options').val();
//or
var $('#options :selected').text();
});
Unless the script is executing too early your code should work.
Upvotes: 1
Reputation: 8206
you can do one of two ways (both demo'd below, check console.log)
you can listen to the .change()
of the select
element you have and then find the value of the selected option
or you can go through each option and find it's corresponding values
$(document).ready(function() {
$('#options').on('change', function() {
console.log($(this).val());
});
$('#options option').each(function() {
console.log('option value: '+ $(this).val());
});
});
<select id="options">
<option value=1>1</option>
<option value=2>2</option>
</select>
Upvotes: 0
Reputation: 1756
You need to get the value of the selected option
$("#options option:selected").val()
Upvotes: 0