开发者

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

开发者 https://www.devze.com 2022-12-15 03:51 出处:网络
So as I click the button, the javascript adds new fields. Currently it adds the new text box to th开发者_如何学Ce side.. is there a way to make it add below? I guess as if there were a .

So as I click the button, the javascript adds new fields. Currently it adds the new text box to th开发者_如何学Ce 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>


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.


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>


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消