Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating input field for html form... but adding a 'label' for it as well?

I have an html form. When you click the button, a javascript function adds a new field. I'm trying to have the function also add a 'label' for the field as well.

I've tried using document.createElement("LABEL"), but that doesn't let me change the innerHtml (or maybe I'm doing it wrong..), nor add a closing

Here is my code. Thanks! var instance = 2;

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

            document.body.insertBefore(document.createElement("BR"), element);
            document.body.insertBefore(newInput, element);

        }
    </script>
</head>


<body>
    <LABEL for="text1">First name: </LABEL>
    <input id="text1" type="text" name="text1">
    <LABEL for="text2">Last name: </LABEL>
    <input id="text2" type="text" name="text2">



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

like image 302
Matt Avatar asked Dec 23 '09 06:12

Matt


2 Answers

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

                    var label = document.createElement("Label");

                    label.htmlFor = "text" + instance;
                    label.innerHTML="Hello";
                    instance++; 

                    document.body.insertBefore(document.createElement("BR"), element);
                    document.body.insertBefore(newInput,element);
                    document.body.insertBefore(label, newInput);

Note that for attribute of the label tag, corresponds to the property htmlFor fo the label object in javascript

like image 123
Vincent Ramdhanie Avatar answered Oct 27 '22 20:10

Vincent Ramdhanie


The example from Vincent does not work.

Try this:

var newlabel = document.createElement("Label");
    newlabel.setAttribute("for",id_from_input);
    newlabel.innerHTML = "Here goes the text";
parentDiv.appendChild(newlabel);
like image 30
Dinkheller Avatar answered Oct 27 '22 20:10

Dinkheller