0

i am trying to create dynamic textboxes. The textbox should be created only if the previous textbox is non-empty. So far i have done this

<!DOCTYPE html> <html> <head> <script> var i=0; function myFunction() { var box = document.createElement("input"); box.type = "text"; var str=box+i; if(i==0) { document.body.appendChild(box); } else if(document.getElementById('str').value!=0) { document.body.appendChild(box); } i++; } </script> </head> <body> <input type="button" id="button" onclick="myFunction()" value="Show box" /> </body> </html> 

but str is not recognised as element id. Any help will be appreciated.

3
  • What are you trying to do? There's no element on your page with ID str and you're not assigning IDs to any elements you create. Also, both branches of your if statement are doing the same thing. Commented Oct 8, 2013 at 16:00
  • box is a reference to a dom element, not a string. Commented Oct 8, 2013 at 16:01
  • str='box'+i; is closer to what you seek i guess Commented Oct 8, 2013 at 16:03

2 Answers 2

1
var i = 0; function myFunction() { var lastInput = document.getElementById('box' + i); if (!lastInput) { // always put first input document.body.appendChild(createInput(0)); } else if (lastInput.value != 0) { // append another one only if previous input content is non-null i++; document.body.appendChild(createInput(i)); } } function createInput(i) { var box = document.createElement("input"); box.type = 'text'; box.id = 'box' + i; box.value = 0; return box; } 
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, its working. Thank you. well,i managed to fix my code also.. :)
Ok, all the best ! so put my anwswer as accepted, and if your final solution is significatively different, edit your post to add the solution you came to. Cheers.
0

Your wrongs:

  1. str = 'box' + i;

  2. Forget to assign box.id = str

  3. Use getElementById(str) instead of getElementById('str')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.