使用 Jquery 在表中设置下拉列表的选定值

我正在使用 jquery wit dropdownlist 添加一个表行,如下所示 -


$.each(data, function (i, item) {

$('#tableRM > tbody:last-child').append('<tr sn=' + item.SN + '>

<td>

<select name="RMLotName" class="form-control lotColumns">

<option value="">Select</option>

<option value="Lot1">Lot1</option>

<option value="Lot2">Lot2</option>

<option value="Lot3">Lot3</option>

</select>

</td>

    <td><input name="RMLotQty" type="text" disabled class="form-control lotColumns" value="' + item.LotQty + '" /></td>


</tr>)

    

    }

现在我想选择下拉列表的默认值,Name = #RMLotName 我尝试过:-


$('#RMLotName').val("'" + item.LotName+"'");


$("#RMLotName option[value='" + item.LotName+"']").attr('selected', 'selected');

但它不起作用。我已经搜索了一段时间,发现了一些像This This和其他的链接,但它们都没有工作。


喵喵时光机
浏览 106回答 1
1回答

PIPIONE

考虑在附加该对象之前从行 html 中创建一个 jQuery 对象。它允许您在该特定行上使用 jQuery 方法。那么你需要一个更好的选择器<select>$.each(data, function (i, item) {&nbsp; &nbsp; &nbsp; let rowHtml = `<tr sn="${item.SN}"><td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <select name="RMLotName" class="form-control lotColumns">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="">Select</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="Lot1">Lot1</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="Lot2">Lot2</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="Lot3">Lot3</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </select>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><input name="RMLotQty" type="text" disabled class="form-control lotColumns" value="${item.LotQty}" /></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>`;&nbsp; &nbsp; &nbsp; // create object from html string&nbsp; &nbsp; &nbsp; let $row = $(rowHtml)&nbsp; &nbsp; &nbsp; // set value of the select within this row instance&nbsp; &nbsp; &nbsp; $row.find('select.lotColumns').val(item.LotName);&nbsp; &nbsp; &nbsp; // append updated object to DOM&nbsp; &nbsp; &nbsp; $('#tableRM > tbody:last-child').append($row);&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript