I want an element with an onclick attribute. When I use jQuery, it doesn’t seem to work. Here is my code:
$("h1").append($("<input>", {type: "text", onclick: "alert();"}));
The following code does work:
<input type="text" onclick="alert();"></input>
you really don’t want the
onclickattribute, you want to use jQuery’sclickevent. Setting theonclickattribute works in most browsers, but it wouldn’t be taking advantage of jQuery’s normalized events and cross-browser support.Also, you’re not using the jQuery factory method correctly, the second argument it takes is the context for the selector, or, in the case where you’re creating html, the owner document for the element to be created in. You really should spend some time reading through the api.
You can chain most methods in jQuery, so the “jQuery way” of doing what you want is: