2

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??

6
  • 3
    The event expects a function, not a string. Commented Aug 29, 2014 at 6:10
  • 2
    What elclanrs has said + an event handler set by property does not reflect to the attributes. Commented Aug 29, 2014 at 6:12
  • @elclanrs the function is designed to create an input element with the attributes of type="text" name="input_0" palceholder="Notes" onkeydown="tab()" but when I tell it to add the onkeydown attribute it doesn't register so how do I add this?? Commented Aug 29, 2014 at 6:13
  • when you add a listener via javascript to an element, the resultig html won't change - ever worked with jquery? you'll see it. Commented Aug 29, 2014 at 6:14
  • 1
    There seems to be a correct answer below : ). Some good reading about events. Commented Aug 29, 2014 at 6:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

unfortunately when I run that script the whole input dissapears.
Don't copy the whole thing from Fiddle - just the line of code, input.onkeydown = tab;. I needed the whole code to show how it works.
the problem is if the function for tab hasn't been created then the function fails and the element not created
Yes, sorry I assumed you already had the function created. You'll need to have it created before you declare your input.
@Jdoonan if my answer helped you, please mark it as the correct one. It helps both of our reputations on StackOverflow and betters the community.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.