[英]Update element index on select option selection using jQuery
我有一個基本表:
<table>
<tr>
<td class="priority-select"><select></select></td>
</tr>
<tr>
<td class="priority-select"><select></select></td>
</tr>
<tr>
<td class="priority-select"><select></select></td>
</tr>
<tr>
<td class="priority-select"><select></select></td>
</tr>
</table>
對於每個".priority-select select"
元素,我需要在選項標簽后附加索引值,並在當前索引后附加selected屬性。 例:
<table>
<tr>
<td class="priority-select">
<select>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
............. to n rows
</table>
我正在使用此代碼段來做到這一點:
var $selects = $(".select");
var selCount = $selects.length;
for(var i=1; i<=selCount; i++){
$selects.append("<option value='" + i + "'>" + i + "</option>");
};
我不知道如何開始下一部分,即根據用戶所做的選擇更新表行。
也就是說,用戶在第三行的選擇中進行選擇,將該行從訂單中刪除,設置為第一行,然后對所有行進行重新排序並重新索引,以便在下一個選擇中,用戶將能夠更改訂單並獲得訂單對。 這將在選擇選項之后完成,而不必提交其他任何內容。
任何幫助,將不勝感激。
您的問題暗示您已經在根據索引選擇適當的數字,但是我在您的代碼中看不到。 您可以按照以下步驟進行操作:
function renumber() {
// select the appropriate number for each
$("select").val(function (i) {
return i + 1;
});
}
然后進行重新排序:
$selects.change(function () {
var $this = $(this);
var val = $this.val();
var $row = $this.closest("tr");
var $parent = $row.parent();
$row.detach();
var $nextRow = $parent.find("tr:eq(" + (val-1) +")");
if($nextRow.length > 0){
$nextRow.before($row);
} else {
$parent.append($row);
}
renumber();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.