javascript tutorial - [Solved-5 Solutions] jQuery Get Selected Option from Dropdown - javascript - java script - javascript array
Problem:
Usually We use $("#id").val() to return the value of the selected option, but this time it doesn't work. The selected tag has the id aioConceptName
Html code
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
click below button to copy the code. By JavaScript tutorial team
Solution 1:
For dropdown options we probably want something like this:
var conceptName = $('#aioConceptName').find(":selected").text();
click below button to copy the code. By JavaScript tutorial team
The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.
Solution 2:
Set the values for each of the options
<select id="aioConceptName">
<option value="0">choose io</option>
<option value="1">roma</option>
<option value="2">totti</option>
</select>
click below button to copy the code. By JavaScript tutorial team
$('#aioConceptName').val()
didn't work because .val() returns the value attribute. To have it work properly, the value attributes must be set on each <option>.
Now we can call $('#aioConceptName').val()
instead of all this :selected voodoo being suggested by others.
Solution 3:
WE stumbled across this question and developed a more concise version of Elliot BOnneville's answer:
var conceptName = $('#aioConceptName :selected').text();
click below button to copy the code. By JavaScript tutorial team
or generically:
$('#id :pseudoclass')
click below button to copy the code. By JavaScript tutorial team
Solution 4:
Try this for value...
$("select#id_of_select_element option").filter(":selected").val();
click below button to copy the code. By JavaScript tutorial team
or this for text...
$("select#id_of_select_element option").filter(":selected").text();
click below button to copy the code. By JavaScript tutorial team
Solution 5:
Have we considered using plain old javascript?
var box = document.getElementById('aioConceptName');
conceptName = box.options[box.selectedIndex].text;