Reputation: 116433
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>
Upvotes: 0
Views: 1804
Reputation: 179264
you really don't want the onclick
attribute, you want to use jQuery's click
event. Setting the onclick
attribute 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:
$('<input>').attr('type', 'text').click(function(){alert();}).appendTo('h1');
Upvotes: 2
Reputation: 7722
Why not:
$("h1").append($("<input>").attr("type","text").click(function(){alert()}));
Upvotes: 3
Reputation: 76003
How about something like:
$('h1').append('<input type="text">').find('input').live('click', function () { alert('bam'); });
EDIT: Yeah I noticed that David Thomas' comment was correct, just changing the alert to actually output something works fine.
Upvotes: 0