I am attempting to retrieve and set the selected value of a select element (drop down list) with Jquery.
for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.
Any insight into this problem would be much appreciated.
thanks in advance
Source: Tips4all
The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.
ReplyDeleteCheck the Id of the element and also check your markup validates at here at W3c.
Without a valid dom jQuery cannot work correctly with the selectors.
If the id's are correct and your dom validates then the following applies:
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();
to get/set the actual selectedIndex property of the select element use:
ReplyDelete$("#select-id").prop("selectedIndex");
$("#select-id").prop("selectedIndex",1);
$('#myId').val() should do it, failing that I would try:
ReplyDelete$('#myId option:selected').val()
$("#myId").val() should work if myid is the input select element id!
ReplyDeleteThis would set the selected item: $("#myId").val('VALUE')
Suppose you have created a Drop Down list using SELECT tag like as follows,
ReplyDelete<select id="Country">
Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..
var result= $("#Country option:selected").text();
it will work fine.