简体   繁体   中英

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

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

您正在创建TEXT元素,但向其中添加了INPUT元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM