简体   繁体   中英

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.

innerHTML isn't preserving the user input. Rather than using innerHTML, you should create the input as a new element and use appendChild to append the element to your container.

This will leave the other input elements untouched, rather than replacing them with a call to innerHTML.

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

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

Instead of using innerHTML, you can use jQuery.append

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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