简体   繁体   English

如何在JSP中使用JavaScript动态添加文本框

[英]How to add dynamically textbox using javascript in jsp

  • MyJSP MyJSP

     <td id="CardNumLabel" colspan="2" width="300px" align="left"> <input readonly="readonly" type="text" name="Names1" id="cNames1" size="25" value="Cardnumber1" /> <input type="text" name="Values1" id="cValues1" size="25" value="" maxlength="6"/ <input type="hidden" name="Cardnumbersay" id="Cardnumbersay" value="1"> <input type="button" value="+" onClick="addCardnumber();"> </td> 
  • My JavaScript 我的JavaScript

     function addCardnumber() { var cardsay; cardsay = parseInt(document.getElementById('Cardnumbersay').value); if(document.getElementById('cNames'+cardsay.toString()).value=="" || document.getElementById('cValues'+cardsay.toString()).value=="") { alert('NULL'); }else{ cardsay = cardsay+1; CardNumLabel.innerHTML = CardNumLabel.innerHTML+"<input type='text' readonly='readonly' name='Names"+say+"' id='cNames"+cardsay+"' size='25' value='Cardnumber"+cardsay+"' />"+"&nbsp;"+ "<input type='text' name='Values"+say+"' id='cValues"+cardsay+"' size='25' maxlength='6'/><br>"; document.getElementById('Cardnumbersay').value = cardsay; } } 

Hi guys, When I click the "+" button the javascript function adds new textboxes for filling. 嗨,大家好,当我点击“ +”按钮时,javascript函数会添加新的文本框进行填充。 This part is running normally. 该部分运行正常。 The problem is when I click the button for adding second textboxes js adds them but deletes the value which I entered to the first textbox. 问题是当我单击添加第二个文本框的按钮时,js会添加它们,但会删除我输入到第一个文本框的值。 I dont want lose the data when I click add button. 单击添加按钮时,我不想丢失数据。 How to solve it? 怎么解决呢? Thanks 谢谢

You are losing the data which the user already entered in the textboxes because the entire textboxes are getting replaced by newer ones when you modify the innerHTML using the following js code: 您将丢失用户已经在文本框中输入的数据,因为使用以下js代码修改innerHTML时,整个文本框将被更新的文本框替换:

CardNumLabel.innerHTML = CardNumLabel.innerHTML+"<some_html_goes_here>";

Due to the above statement the entire contents of the td having id="CardNumLabel" are replaced by a newer value. 由于上述声明,具有id="CardNumLabel"的td的全部内容将替换为较新的值。 The newer innerHTML put in has the number of textboxes increased by one but no provision to retain the content previously entered by the user in the textboxes. 内置的较新的innerHTML的文本框数量增加了一个,但未保留用户先前在文本框中输入的内容。

To retain the previous entered data content: 保留先前输入的数据内容:

  1. Use appendChild() method instead of modifying innerHTML directly 使用appendChild()方法,而不是直接修改innerHTML
  2. Or, Write a loop in js to copy the data entered by the user and store it in an array. 或者,在js中编写一个循环以复制用户输入的数据并将其存储在数组中。 Then use the same innerHTML way to increase the number of textboxes and then write another loop to put back the data from the array into the text-boxes 然后使用相同的innerHTML方式增加文本框的数量,然后编写另一个循环以将数组中的数据放回文本框

Hope I helped! 希望我能帮上忙!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM