I have a drop down list that fetches values from db as follows
$.get('/getJobs', function (jobs) {
seljobs = jobs;
var i = 0;
jobs.forEach(function (n) {
alert("job id----"+n.id)// 32,67,45
alert("job names----"+n.names)//test1,test2,test3
html += '<option value="' + i + '">' + n.names + '</option>';
i++;
});
$('#jobSel').html(html);
});
i have to get the id
of selected dropdown value..
ic in my dropdown i have name values test1,test2,test3
ans assosiated id's 32,67,45,
while selecting test1 i have to get id 32 and so ans so.How it is possible
<tr>
<td width="200px">Jobs</td>
<td>
<select id="jobSel" class="longcombo"></select>
</td>
</tr>
This question is related to
javascript
jquery
Try this
on change event
$("#jodSel").on('change',function(){
var getValue=$(this).val();
alert(getValue);
});
Note: In dropdownlist
if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id
attribute inside option its not standard paractise though i did both in my answer but i prefer example 1
HTML Markup
Example 1:
<select id="example1">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
Example 2 :
<select id="example2">
<option id="1">one</option>
<option id="2">two</option>
<option id="3">three</option>
<option id="4">four</option>
</select>
Jquery:
$("#example1").on('change', function () {
alert($(this).val());
});
$("#example2").on('change', function () {
alert($(this).find('option:selected').attr('id'));
});
View Demo : For example 1 & 2
Blog Article : Get and Set dropdown list selected value with Jquery
My Blog : jQuery tutorials
Try the change event and selected selector
$('#jobSel').change(function(){
var optId = $(this).find('option:selected').attr('id')
})
First set a custom attribute into your option for example nameid
(you can set non-standardized attribute of an HTML element, it's allowed):
'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
then you can easily get attribute value using jquery .attr()
:
$('option:selected').attr("nameid")
For Example:
<select id="jobSel" class="longcombo" onchange="GetNameId">
<option nameid="32" value="1">test1</option>
<option nameid="67" value="1">test2</option>
<option nameid="45" value="1">test3</option>
</select>
Jquery:
function GetNameId(){
alert($('#jobSel option:selected').attr("nameid"));
}
If you are trying to get the id, then please update your code like
html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';
To retrieve id,
$('option:selected').attr("id")
To retrieve Value
$('option:selected').val()
in Javascript
var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;
Source: Stackoverflow.com