[問題] 如何讓使用者已輸入的內容不消失

看板Ajax作者 (ViperLiu)時間8年前 (2015/08/28 13:15), 8年前編輯推噓3(307)
留言10則, 5人參與, 最新討論串1/1
我用HTML設計了一個表單如下 <table id="table" style="float:inherit"> <tr><th>物品名稱</th><th>數量</th><th>小計</th></tr> <tr> <td><input type="text" name="item[]" require></td> <td><input type="text" name="many[]" require></td> <td><input type="text" name="total[]" require></td> </tr> </table> <input type="button" id="btn1" value="新增一項物品"><br/> 預設是只有一欄可以讓使用者輸入 因為不知道使用者有多少筆資料要輸入,所以我設計一個按鈕讓使用者自行新增輸入欄位 如下: <script> window.onload = function(){ document.getElementById("btn1").onclick = newitem; }; function newitem(){ document.getElementById("table").innerHTML+= "<tr><td><input type=\"text\" name=\"item[]\" require></td> <td><input type=\"text\" name=\"many[]\" require></td> <td><input type=\"text\" name=\"total[]\" require></td></tr>"; } </script> 可是,如果使用者已經輸入了內容在原有的欄位裡面 按下按鈕新增欄位之後,原本已經輸入的內容就會被清空 能有什麼解決的辦法嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.130.225.223 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1440738946.A.668.html ※ 編輯: a0960330 (220.130.225.223), 08/28/2015 13:18:34 ※ 編輯: a0960330 (220.130.225.223), 08/28/2015 13:19:20

08/28 13:20, , 1F
改 innerHTML 元件會重繪,用 appendChild 應該可行
08/28 13:20, 1F

08/28 13:20, , 2F
但我好像有在 IE 遇過 tbody 不給改的狀況就是了.
08/28 13:20, 2F
謝謝您,我去研究看看 ※ 編輯: a0960330 (220.130.225.223), 08/28/2015 13:24:40 ※ 編輯: a0960330 (220.130.225.223), 08/28/2015 13:27:06

08/28 15:30, , 3F
一樓正解 不過你可以考慮用jQuery 會輕鬆非常多
08/28 15:30, 3F

08/28 15:30, , 4F
或者類似工具
08/28 15:30, 4F

08/28 23:45, , 5F
$(document).find('input').each(function{$(this).Val(
08/28 23:45, 5F

08/28 23:45, , 6F
'')})
08/28 23:45, 6F

08/30 21:54, , 7F
用jquery append吧!
08/30 21:54, 7F

09/02 23:37, , 8F
appendChild就可以了,不用特別載入jquery
09/02 23:37, 8F

09/02 23:41, , 9F
用變數存document.createElement('tr'),再塞innerHTML
09/02 23:41, 9F

09/02 23:41, , 10F
然後用appendChild加到table裡面
09/02 23:41, 10F
文章代碼(AID): #1Lt-w2Pe (Ajax)