Randomblue
Randomblue

Reputation: 116433

jQuery <input> element problem with onclick attribute

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

Answers (3)

zzzzBov
zzzzBov

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

rabudde
rabudde

Reputation: 7722

Why not:

$("h1").append($("<input>").attr("type","text").click(function(){alert()}));

Upvotes: 3

Jasper
Jasper

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

Related Questions