Ren DF Ren DF - 5 months ago 17
HTML Question

dynamic textbox in pressing enter key

can someone help me with my code? everytime I type in my textbox it create multiple textbox but I want to create a program that everytime I hit enter key it create another textbox.

here's my code:

<script language="javascript">
function changeIt() {
var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i><br/>"
}
</script>
<body>
<form name="form" action="post" method="">
<input type="text" name=t1 onkeydown="changeIt()">
<div id="my_div"></div>
</form>
</body>

Lal Lal
Answer

See this fiddle

What you have done in your code was to create a textfield whenever a key press occurs..To create a textfield only when enter key is pressed you have to check the keycode of the pressed button.

So, Please change your JS a little bit as follows..

function changeIt(event) {
  var key = event.which || event.keyCode;
  if (key == '13') {
    var i = 1;
    my_div.innerHTML = my_div.innerHTML + "<br><input type='text' name='mytext'+ i><br/>"
  }
}

Please make sure that you replace your <input> also as follows

<input type="text" name=t1 onkeydown="changeIt(event)">

Please read more about keyCode in the docs.. Also, if you want to find out the keyCode of any button, please check keycode.info