2016-02-18 55 views
0

在jQuery中,如果我有一个id为“parentId”的html选择,如何选择一个我知道选项值的选项?如何在HTML选择中选择一个我知道该值的选项?

这里是我的代码:

function selectParentId(parentId) 
{ 
    $('#parentId').find('option').each(function(index,element){ 
    if(element.value == parentId) 
     element.prop('selected', true); 
    }); 
} 

如何需要改变上面的代码?

+0

复制 - > http://stackoverflow.com/questions/13343566/set-select-option-selected-by-value – adeneo

回答

2

要使用值选择一个项目,你可以试试这个:

$('#parentId option[value="yourvalue"]').prop("selected", 1); 

所以你的函数可以重新写为:

function selectDropdown(id, value) 
{ 
    $('#'+id+' option[value="'+value+'"]').prop("selected", 1); 
} 

所以,你可以这样调用它:

selectDropdown('theIdOfSelect', 'theValueOfSelect'); 

实例Here

+1

你打我吧。但这里有一些非常类似的东西:https://jsfiddle.net/174qp30p/4/ – WheretheresaWill

+1

我已经更新了小提琴@Wheretheresa,如果我的动态更加动态,可以选择任何'select' :-) –

0

试试这个:

function selectParentId(id,value) { 
    $('#' + id).val(value) 
} 
相关问题