3

I am trying to create textboxes inside <div id="screens"> </div>. I have a drop down menu for which I select the number of textboxes to be created.

The JavaScript code I've written here is not working:

code:

function create(param) {
    document.getElementById("screens").innerHTML="";          
    for(var i = 0; i < param; i++) {
        alert(i);
        document.write('<input type="text" name="Fname">');
    }
}

This is adding textboxes by clearing all contents of the current page, but I want the textboxes to be added to <div id="screen"> </div>. How can I do this?

1
  • Please read some documentation about document.write(). You've used innerHTML in your code, why not to reuse it? Commented Aug 20, 2013 at 4:34

5 Answers 5

7

Try something like this:

function create(param) {
    var s= "";
    for(var i = 0; i < param; i++) {
        s+= '<input type="text" name="Fname">'; //Create one textbox as HTML
    }
    document.getElementById("screens").innerHTML=s;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since you've tagged jQuery in your question, I'll assuming that you're using jQuery.

function create(param) {
    'use strict';

    var i;

    $("#screens").empty();

    for(i = 0; i < param; i += 1) {
        $('#screens').append('<input type="text" name="Fname">');
    }
}

jsFiddle

A pure JavaScript implementation would look like this:

function create(param) {
    'use strict';

    var i, target = document.getElementById('screens');
    target.innerHTML = '';

    for(i = 0; i < param; i += 1) {
        target.innerHTML += '<input type="text" name="Fname">';
    }
}

jsFiddle

Comments

0
function create(param) {
    var screens = document.getElementById('screens'),
        innerHTML = '',
        i;

    for (i = 0; i < param; i += 1) {
        alert(i);
        innerHTML += '<input type="text" name="Fname">';
    }

    screens.innerHTML = innerHTML;
}

Comments

0
function create(param) {
    var target = document.getElementById('screens'),
        oFrag=document.createDocumentFragment();

    target.innerHTML = '';

    for (var i = 0; i < param; i++) {
        var iptNode = document.createElement("input");
        iptNode.setAttribute("type", "text");
        iptNode.setAttribute("name", "Fname");
        oFrag.appendChild(iptNode);
    }

    target.appendChild(oFrag);
}

Comments

0
<script>
var newInput4=document.createElement("input");
newInput4.className="form-control ";
newInput4.name="totalunit"+instance;
newInput4.placeholder="Unit";   
newInput4.type="text";
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.