2016-02-18 48 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) 
} 
相關問題