Jimmy
Jimmy

Reputation: 2925

How to add an HTML form element dynamically using javascript

I'm trying to add a text field to a form dynamically using javascript. From what I can tell, my code should work.

function change()
{
textField = document.createElement("text");
textField.id="sub"+count;
textField.name="sub"+count;
textField.value="Enter a name for another new subcategory";
textField.size="35";
textField.onchange="javascript:change()";
textField.onFocus="javascript:clearField()";
document.getElementById("addCatForm").appendChild(textField);
}

Upvotes: 1

Views: 2041

Answers (2)

Peter Ajtai
Peter Ajtai

Reputation: 57715

You're creating a TEXT element, but adding things to it for an INPUT element.

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30092

You want:

var field = document.createElement('input');
field.type = 'text';

NB if you're doing lots of Javascript development, you might want to use a framework, such as ExtJS

The code to do it would be:

var field = Ext.get('form').createChild({
    tag: 'input'
    //other options
});
field.on('change', change);
field.on('focus', focus);

Upvotes: 2

Related Questions