Reputation: 17
I have been tasked with creating a dynamic form
using jQuery. Once I have created the form I need to send the form to a div
tag declared in the body
. I am under no circumstances allowed to declare the form in the body of the HTML. The form is created in the script and displayed in the body.
var frm = $("<form id=searchform></form>");
$("#searchform").append(txt4, txt3, txt5, txt6); // txt4 etc, are elements added to the form
$("#reports2").html("#searchform");// SOMETHING NOT QUITE RIGHT HERE!
reports2
is declared as a div in the body, code above is in a script locally. Any help or pointers would be appreciated.
Upvotes: 1
Views: 436
Reputation: 337560
You need to provide the frm
variable to the append()
method, not the string selector for the element which is not yet in the DOM, and not to the html()
method as that expects a string. Try this:
var $frm = $("<form id=searchform></form>");
$frm.append(txt4, txt3, txt5, txt6);
$("#reports2").append($frm);
Or alternatively:
var $frm = $('<form id="searchform"></form>');
$frm.append(txt4, txt3, txt5, txt6).appendTo('#reports2');
Both of the above are logically the same, the latter is just shorter due to the chained method calls. Note the $
before the variable name is a naming convention used to denote that the variable holds a jQuery object.
Upvotes: 5