Search code examples
javascriptformsinputonkeypress

Javascript append input to form


I have this Script:

var countBox = 0;

function addInput() {
var breakNode = document.createElement("br");

var input = document.createElement("input");
input.type = "text";
input.name = "input_" + countBox.toString();
input.placeholder = "Notes";
input.onkeydown = "tab()";

var container = document.getElementById('container');
container.appendChild(breakNode);
container.appendChild(input);

countBox += 1;
}

it should return

<input type="text" name="input_0" placeholder="Notes" onkeydown="tab()">

but it only returns

<input type="text" name="input_0" placeholder="Notes">

But the input.onkeydown doesn't work is there a way to create the first element preferably with Javascript so I can dynamically create a new field when the user presses enter??


Solution

  • What you want is input.onkeydown = tab;.

    Here's a fiddle that shows it in action.

    In Javascript, and Python and many other scripting languages, functions can be passed as arguments or parameters. Here, we are passing the function tab() as the value for the onkeydown attribute.