[英]Dynamically create new fields to submit multiple row entries into the table model
[英]Update specific row of table of multiple entries
我有一張顧客桌子。 每個客戶都有名字和姓氏。 該表的兩個文本字段是可編輯的。 因此,用戶可以在按保存時更新信息。 問題是我無法獲取特定的行信息,只能獲取第一行結果
我嘗試將名稱與輸入字段匹配,但沒有成功。
<?php foreach($customer as $each){ ?>
<td class="first_name" id="first" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" id="last" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td > <button type="button" onclick="save('<?php echo $each['first_name'];?
>','<?php echo $each['last_name'];?>');" >Save</button></td>
<? } ?>
<script type="text/javascript">
function save(first,second) {
<?php foreach($customer as $each){?>
var first_name = "<?php echo $each['first_name']?>";
var last_name = "<?php echo $each['last_name']?>";
if (first_name==first && last_name == second){
var fname = document.querySelectorAll(".first_name");
console.log(fname[0]);
}
<?php } ?>
}
</script>
您將不得不使用其他查詢選擇器。 為要選擇的元素分配一個類名或屬性(例如,使用.name
進行查詢的name
),然后querySelectorAll
方法將返回與查詢匹配的元素數組。
我看到的主要問題是,您使用php
在javascript
函數內創建了不必要的foreach
循環。
您可以動態創建表及其中的內容,這很好。 但是javascript並不關心這一點,因此您不應該使用php創建javascript。 所以我會這樣做。
我將td封裝在tr的原因中,我假設您將這些數據放入tr中。
<?php foreach($customer as $each){ ?>
<tr class="customer-row">
<td class="first_name" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td><button type="button" class="save">Save</button></td>
</tr>
<? } ?>
然后在php foreach循環之外,我將創建我的腳本。
<script type="text/javascript">
var saveBtn = document.querySelectorAll(".save");
for(var i = 0; i < saveBtn.length; i++) {
// attach click event to every button.
saveBtn[i].addEventListener("click", function() {
var _this = this;
var _tr = _this.closest(".customer-row");
var fname = _tr.querySelector(".first_name").innerText;
var lname = _tr.querySelector(".last_name").innerText;
console.log("Name: ", fname + " " + lname");
// below you can implement your check name logic...
}
}
</script>
我不確定我的js是否不會引發錯誤,但不能100%地確定您應該將server-side
client-side
邏輯與client-side
邏輯分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.