简体   繁体   English

在javascript中创建新文本框后保存用户输入

[英]saving user input after creating new textbox in javascript

When a user presses the "New Box" after entering information in previous boxes created, I don't want the old data entered by the user to be erase when the New Box button is pressed. 当用户在先前创建的框中输入信息后按下“新建框”时,我不希望在按下“新建框”按钮时删除用户输入的旧数据。 How do I save the old user entered data when a new TextBox is created? 创建新的TextBox时如何保存旧的用户输入数据?

 <html> <head> <script> var boxCount=1; var boxName=0; function newBox(){ var boxName="Box_"+boxCount; document.getElementById('box').innerHTML+='<br><input type="text" name="'+boxName+'" placeholder="'+boxName+'"/><br>'; boxCount+=1; } </script> </head> <body> <button type="button" onclick="newBox()">New Box</button> <form action="#" method="post"> <span id="box"></span><br> <input type="submit" value="Submit"> </form> </body> </html> 

element.innerHTML destroys all element's childs. element.innerHTML销毁所有element的孩子。

If you want to keep child elements, you need to use DOM functions. 如果要保留子元素,则需要使用DOM函数。 element.appendChild() is what you are looking for. 您正在寻找element.appendChild()。

<html>
<head>
    <script>
        var boxCount=1;
        var boxName=0;

        function newBox()
        {
            var input           = document.createElement("input");
            input.type          = "text";
            input.name          = "Box_" + boxCount;
            input.placeholder   = "Box_" + boxCount;
            document.getElementById('box').appendChild(input);

            var new_line = document.createElement("br");
            document.getElementById('box').appendChild(new_line);

            boxCount++;
        }
        </script>

    </head>
    <body>
        <button type="button" onclick="newBox()">New Box</button>
        <form action="#" method="post">
            <span id="box"></span><br>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

Also, you can get all textbox values on server side, as an array, by replacing input.name = "Box_" + boxCount; 另外,您可以通过替换input.name = "Box_" + boxCount;来获得服务器端所有文本框的值作为数组input.name = "Box_" + boxCount; by input.name = "Box[" + boxCount + "]" . 通过input.name = "Box[" + boxCount + "]" Sometimes dealing with this one is easier. 有时处理这一问题会更容易。

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

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