using javascript to add form fields.. but below, not to the side?

非 Y 不嫁゛ 提交于 2020-01-07 03:18:05

问题


So as I click the button, the javascript adds new fields. Currently it adds the new text box to the side.. is there a way to make it add below? I guess as if there were a
. Here is the code. Thanks!

<html>
<head>
    <script type="text/javascript">
        var instance = 1;

        function newTextBox(element)
        {       
            instance++; 
            var newInput = document.createElement("INPUT");
            newInput.id = "text" + instance;
            newInput.name = "text" + instance;
            newInput.type = "text";
            //document.body.write("<br>");
            document.body.insertBefore(newInput, element);
        }
    </script>
</head>


<body>
    <input id="text2" type="text" name="text1"/> <br>
    <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
</body>


回答1:


Insert a <br/> tag infront of the inserted input or better yet, put the input into a div and control the look of it with CSS.




回答2:


Add this to the end of your function:

document.body.insertBefore(document.createElement("br"), element);

Full code:

<html>
<head>
        <script type="text/javascript">
                var instance = 1;

                function newTextBox(element)
                {               
                        instance++; 
                        var newInput = document.createElement("INPUT");
                        newInput.id = "text" + instance;
                        newInput.name = "text" + instance;
                        newInput.type = "text";
                        //document.body.write("<br>");
                        document.body.insertBefore(newInput, element);

                        document.body.insertBefore(document.createElement("br"), element);
                }
        </script>
</head>


<body>
        <input id="text2" type="text" name="text1"/> <br>
        <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
</body>
</html>



回答3:


Just create a <br> element the same way and put it between.

var newBr = document.createElement("BR");
document.body.insertBefore(newBr, element);

Or use CSS. The display:block may be of value.




回答4:


You could either, insert br element after the new input, or wrap it inside a div element:

function newTextBox(element) {                
    instance++; 
    var newInput = document.createElement("INPUT"); 
    newInput.id = "text" + instance; 
    newInput.name = "text" + instance; 
    newInput.type = "text"; 

    var div = document.createElement('div'); 
    div.appendChild(newInput); 
    document.body.insertBefore(div, element); 
} 

Check the above example here.



来源:https://stackoverflow.com/questions/1950837/using-javascript-to-add-form-fields-but-below-not-to-the-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!