Ani
Ani

Reputation: 197

how to combine two vars in javascript?

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.

Upvotes: 0

Views: 91

Answers (2)

vp_arth
vp_arth

Reputation: 14982

Your wrongs:

  1. str = 'box' + i;

  2. Forget to assign box.id = str

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

Upvotes: 0

GameAlchemist
GameAlchemist

Reputation: 19294

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;
}

Upvotes: 1

Related Questions