如何根据保存的选择框值更改选择框值

时间:2017-05-10 06:53:14

标签: javascript jquery

if (itemPrice != null) {
        var option = null;
        for (var i = 0; i < itemPrice.d.length; i++) {
            option += '<option value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
        }

    } else {
        SessioExp(response.statusText);
    }

    tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';
    $.each(itemLinked, function (k, v) {
        if (d.ItemCode == v.ITEMCODE) {
           //Here set v.PRICELIST TO OPTION VALUE
            if (v.ISLINKED) {
                tblRow += '<td style="width:10%" align="center"><a href="#"><span id="existingData" class="fa fa-times" aria-hidden="false" style="display: none;"></span></a></td>';
                tblRow += '<td style="width:10%" align="center"><input type="checkbox" class="chkLinked" checked /></td>';
                flage = false;
            }
        }
    });

如果(d.ItemCode == v.ITEMCODE)

,我想在条件为真时设置选择框值
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';

这里我们要显示第一个保存的值。

1 个答案:

答案 0 :(得分:0)

假设您生成的选项已附加到html,您只需调用JS函数optionID.selected = true

因此,您需要为所有选项定义ID

// assuming that all your values are unique
for (var i = 0; i < itemPrice.d.length; i++) {
   option += '<option id=' + itemPrice.d[i].ListNum + ' value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
//pass the option id here
//P.S you can only call this funtion only if the options have been appended to the html
function defineOption(optionID) {
     document.getElementById(optionID).selected = true;
}