user1148875
user1148875

Reputation: 459

Multiple dynamic input text javascript

Im having trouble creating multiple input texts with javascript.

My point is create a new input text everytime the input before is completed. (parent?)

Ive some code for comboboxs, but this time I need just input text box.

How can I do that ?

I've found this code:

<script type="text/javascript">
function addInput()
{
    var x = document.getElementById("inputs");
    x.innerHTML += "<input type=\"text\" />";
}
</script>

<input type="button" onmousedown="addInput();" />
<div id="inputs"></div>

But for my problem button is obsolete.

I think my event trigger will be something arround this "when user click in an input text box and it is != blank it creates a new one".

I migth need some ID to identify every input text box.

Cheers.

Upvotes: 2

Views: 11519

Answers (3)

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

JSBIn Demo

Guess this helps:

   <div id="myDiv">
        <input type="text" id="txt_1" onkeydown="newTextBox(this)" />
   </div>

<script type="text/javascript">

function newTextBox(element){
   if(!element.value){
       element.parentNode.removeChild( element.nextElementSibling);
       return;
   }
   else if(element.nextElementSibling)
       return;
    var newTxt = element.cloneNode();
    newTxt.id = 'txt_'+( parseInt( element.id.substring(element.id.indexOf('_')+1)) + 1);
    newTxt.value='';
    element.parentNode.appendChild(newTxt);
}  

</script>

Upvotes: 2

Gareth Cornish
Gareth Cornish

Reputation: 4356

HTML code:

<div id="inputcontainer">
    <input type="text" name="input0" id="input0" onkeyup="addInput();" />
</div>

And Javascript:

var currentindex = 0;
function addInput(){
    var lastinput = document.getElementById('input'+currentindex);
   if(lastinput.value != ''){
        var container = document.getElementById('inputcontainer');
        var newinput = document.createElement('input');
        currentindex++;
        newinput.type = "text";
        newinput.name = 'input'+currentindex;
        newinput.id = 'input'+currentindex;
        newinput.onkeyup = addInput;
        container.appendChild(newinput);
   }
}

This will add a new input to the list only when the last input is not empty.

http://jsfiddle.net/HJbgS/

Upvotes: 2

Chris
Chris

Reputation: 7855

Have a look at the onchange event on your text input field. You can use it, like you use onmousedown on your button.

See http://www.w3schools.com/jsref/event_onchange.asp for an example.

In your addInput() function you should then check if the input of the previous textfield is != "".

Upvotes: 0

Related Questions