简体   繁体   中英

the correct way to append an input element to a form

So far anytime i have needed to add an input to a form dynamically i have done:

 var row = "<input type='text' id='someId' name='someName' value='someValue'>";
 $('#form').append(row);

I know there is a better way. I have read about setAttribute or .attr(). how would i start?

 var input = ???;
  input.attr('type','text');
  input.attr('id','someId');
  input.attr('name','someName');
  input.attr('val','someValue');
  input.attr('type','text');

 $('#form').append(input);

Yes there is a better way exist,

 $('#form').append($("<input>",{
   "type" : "text",
   "id" : "someId",
   "name" : "someName",
   "value" : "someValue"
 }));

Don't mix up pure jquery with javascript. That may results in error sometimes. like invoking jquery functions over node object. Ex : node.css(...)

When I need to add elements dynamically I do the following:

var $_form = $("#form");
$("<input/>",{ id : "input_1",type : "text", val : "value" }).addClass("class1 class2").appendTo($_form);

This form works for any element, not just form fields.

For brevity you can just do the following, all in one line:

$('#form').append("<input type='text' id='someId' name='someName' value='someValue'>");

but for more complex cases you can take the longer approach:

$("<input/>", {
    attributes
});

You can do this using JavaScript's createElement() and setAttribute() , like so:

var input = document.createElement("input");
input.setAttribute("type", "text");
//and so on

As @scottmarcus has pointed out this is is not necessarily better but different. It's what you're looking for:

var input = document.createElement("INPUT");

Which is a DOM element; so you cannot use jQuery methods such as .attr() . You would have to use JavaScript methods such as setAttribute() . In order to use jQuery methods all you have to do is to wrap input in $ like so:

var input = $( document.createElement("INPUT") );

A better way to write this would be:

var input = $('<input/>');

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

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