Jquery从下拉列表中获取所选值的id

我有一个下拉列表,从db中获取值,如下所示

$.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 += '' + n.names + ''; i++; }); $('#jobSel').html(html); }); 

我必须获得所选下拉值的id ..

在我的下拉列表中我有名称值test1,test2,test3和assosiated id's 32,67,45,

选择test1时我必须得到id 32,所以如此。如何可能

  Jobs     

试试这个

关于改变事件

 $("#jodSel").on('change',function(){ var getValue=$(this).val(); alert(getValue); }); 

注意:如果你想在你的数据库中设置id,文本关系,请在dropdownlist ,在选项标签中将id设置为值,而不是通过在选项中添加额外的id属性而不是标准的实践,尽管我在答案中都做了两个但我更喜欢示例1

HTML标记

 Example 1:  Example 2 :  

jQuery的:

 $("#example1").on('change', function () { alert($(this).val()); }); $("#example2").on('change', function () { alert($(this).find('option:selected').attr('id')); }); 

查看演示: 例如1,示例2

博客文章: 使用Jquery获取并设置下拉列表选择的值

学习jQuery:简单易用的jQuery教程博客

尝试更改事件和选定的选择器

 $('#jobSel').change(function(){ var optId = $(this).find('option:selected').attr('id') }) 

如果您想获取ID,请更新您的代码

  html += ''; 

要检索ID,

 $('option:selected').attr("id") 

检索价值

 $('option:selected').val() 

在Javascript中

 var e = document.getElementById("jobSel"); var job = e.options[e.selectedIndex].value; 

首先在您的选项中设置自定义属性,例如nameid (您可以设置HTML元素的非标准化属性,允许):

 '' 

然后你可以使用jquery .attr()轻松获取属性值:

 $('option:selected').attr("nameid") 

例如:

  

jQuery的:

 function GetNameId(){ alert($('#jobSel option:selected').attr("nameid")); }