Skip to content Skip to sidebar Skip to footer

Add A New Text Field Every Time A Button Is Pressed

i am trying to create a bit of javascript that will create a new text field every time a button is pressed, any help would be appreciated, it seems like the javascript doesn't want

Solution 1:

var answers = 0,
    write = document.getElementById('buttons');

function addAnswer() {
    write.innerHTML += 'Add answer: <input type="text" id="answer"' + answers + '/> <br />';
    answers++;
}​

Solution 2:

I faced the same problem in my college project. You can also accomplish your work as David suggested, but using innerHTML doesn't add elements to DOM and as a result, when you'll refresh the page, text fields will disappear. So for getting persistent text fields, you can use the code mentioned below:

var i = 0;

function addMore()
{
   var x = document.getElementById('buttons');
   var input1 = document.createElement("input");
   input1.setAttribute("type","text");
   input1.setAttribute("name","i" + i );
   x.appendChild( input1 );
   i++;
}  

You can use firebug for debugging javascript things. Thanks.


Solution 3:

function addTextField(id){
    var colors = new Array('#660000','#33ff00','#0066ff','#cc3399','#9966ff');
    var container = document.getElementById(id);
    var ulElement = document.createElement('ul');
    container.appendChild(ulElement);
    var hideLink = function(){
        var firstElement = ulElement.firstChild.getElementsByTagName('a')[0];
            firstElement.style.display = (ulElement.childNodes.length==1)?'none':'inline';
        for(var i = 0 ; i <ulElement.childNodes.length; i++)
            ulElement.childNodes[i].style.color = colors[i%5];
    }
    var addListElement = function(){
        var liElement = document.createElement('li');
        ulElement.appendChild(liElement);
        var textElement = document.createElement('input');
        textElement.setAttribute('type','text');
        liElement.appendChild(textElement);

        var deleteLink = document.createElement('a');
        deleteLink.href = "#";
        deleteLink.appendChild(document.createTextNode('delete'));
        liElement.appendChild(deleteLink);
        deleteLink.onclick = function(){
            ulElement.removeChild(liElement);
            hideLink();
        }
        hideLink();
    }
    addListElement();
    var anchorElement = document.createElement('a');
    anchorElement.href = "#";
    anchorElement.appendChild(document.createTextNode('Add more'));
    container.appendChild(anchorElement);
    anchorElement.onclick = addListElement;
    hideLink();

}

Here is the Demo http://jsfiddle.net/mannejkumar/cjpS2/


Post a Comment for "Add A New Text Field Every Time A Button Is Pressed"