jQuery append breaks my HTML form (with submit button)
I'm trying to create a form with a submit button via jQuery using append(). So the following:
out.append('<form name="input" action="/createuser" method="get">');
out.append('Username: <input type="text" name="user" />');
out.append('<input type="submit" value="Submit" />');
out.append('</form>');
However, clicking on submit, nothing happens!
However if I do the following:
var s =
'<form name="input" action="/createuser" method="get">' +
开发者_高级运维'Username: <input type="text" name="user" />' +
'<input type="submit" value="Submit" />' +
'</form>';
out.html(s);
Then the submit button works fine!
I'm happy to use the 2nd method, but would rather know what the problem is here.
Thanks
With:
out.append('<form name="input" action="/createuser" method="get">');
the form DOM element is automatically closed by the browser so everything else is added as new DOM elements but not inside the form.
Here's an alternative method which I like for working with the DOM tree:
out.append($('<form/>', {
name: 'input',
action: '/createuser',
method: 'get',
html:
$('<span/>', {
html: 'Username: '
})
.after(
$('<input/>', { type: 'text', name: 'user' })
.after(
$('<input/>', { type: 'submit', value: 'Submit' })
)
)
}));
Append works a bit different:
// create your element first
var form = $('<form name="input" action="/createuser" method="get"></form>');
// add elements to it
form.append('<form name="input" action="/createuser" method="get">');
form.append('Username: <input type="text" name="user" />');
form.append('<input type="submit" value="Submit" />');
// and only then append it to your html
out.append(form);
Try this instead. As Darin Dimitrov said, elements are auto-closed when appended.
Method chaining makes things quite a bit neater:
$('<form name="input" action="/createuser" method="get" />')
.append('Username: <input type="text" name="user" />')
.append('<input type="submit" value="Submit" />')
.appendTo(out);
This example work perfectly:
HTML
<body></body>
Script with JQuery
$(document).ready(function(){
var form=" ";
form+='<form>';
form+='<form name="input" action="/createuser" method="get">';
form+='Username:<input type="text" name="user" /><br/>';
form+='<input type="submit" value="Submit" />';
form+='</form>';
$("body").append(form);
});
精彩评论