简体   繁体   English

使用Javascript动态添加文本框中消失的文本

[英]Disappearing text in dynamically added textboxes with Javascript

You can add as many text boxes as you want as shown by using the following code 您可以使用以下代码添加任意数量的文本框,如下所示

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
var i=2;
function AddTextbox(){
container.innerHTML=container.innerHTML+'<input type="text" name="'+ i + '" id="'+ i + '">' + '</br>';
i++;
}
</script>

</head>
<body>
<form action="next.php" method="post" >
<input type="text" name="1" id="1" />
<input type="button" onClick="AddTextbox();" value="add" />
<input type="submit" value="submit" />
<div id="container"></div>
</form>
</body>
</html>

The only issue that I'm getting is, if the user has added 2 text boxes and also has written something in those text boxes and the user again clicks on the 'add text box' button then the data inserted by the user into the textboxes disappears. 我得到的唯一问题是,如果用户添加了2个文本框并且还在这些文本框中写了一些内容,并且用户再次单击“添加文本框”按钮,则用户将数据插入到文本框中消失。

innerHTML isn't preserving the user input. innerHTML不保留用户输入。 Rather than using innerHTML, you should create the input as a new element and use appendChild to append the element to your container. 您应该将输入创建为新元素,并使用appendChild将元素追加到容器中,而不是使用innerHTML。

This will leave the other input elements untouched, rather than replacing them with a call to innerHTML. 这将使其他输入元素保持不变,而不是通过调用innerHTML来替换它们。

而不是设置container.innerHTML,因为您之前已经引用了jQuery,请执行以下操作:

$(container).append('<input type="text" ...etc...

Instead of using innerHTML, you can use jQuery.append 您可以使用jQuery.append而不是使用innerHTML

Check the Fiddle here 在这里检查小提琴

使用jQuery更容易解决问题

$('#container').append('<input type="text"  ');

Change your button name like follows: 更改您的按钮名称,如下所示:

<input type="submit2" onClick="AddTextbox();" value="add" />

instead of 代替

<input type="button" onClick="AddTextbox();" value="add" />

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

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