如何在html选择中选择我知道值的选项?

时间:2016-02-18 02:08:32

标签: jquery html-select

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

以下是我的代码:

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

我如何更改上述代码?

2 个答案:

答案 0 :(得分:2)

要使用值选择项目,您可以尝试:

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

所以你的功能可以重写为:

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

所以你可以这样称呼:

selectDropdown('theIdOfSelect', 'theValueOfSelect');

示例Here

答案 1 :(得分:0)

试试这个:

function selectParentId(id,value) {
    $('#' + id).val(value)
}