问题描述
我有一个从db获取值的下拉列表,如下所示
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);
});
我必须获得所选的 id
下拉值..
i have to get the id
of selected dropdown value..
我的下拉列表中我有名字值 test1,test2,test3
ans assosiated id's 32,67,45,
ic in my dropdown i have name values test1,test2,test3
ans assosiated id's 32,67,45,
选择test1时我必须得到id 32,所以也是如此。如何可能
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>
推荐答案
试试这个
关于更改事件
$("#jodSel").on('change',function(){
var getValue=$(this).val();
alert(getValue);
});
注意:在下拉列表中
如果你想设置id,来自你的数据库的文本关系,然后在选项标签中将id设置为值,而不是通过在选项中添加额外的 id
属性而不是标准的paractise虽然我在我的回答中都做了但我更喜欢示例1
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标记
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, example 2
博客文章:
Blog Article : Get and Set dropdown list selected value with Jquery
这篇关于Jquery从下拉列表中获取所选值的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!