0

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>
5
  • 2
    Works in Chromium 12/Ubuntu 11.04; and works in Firefox 5, if the alert() is alerting something. Commented Jul 23, 2011 at 18:45
  • on this sort of debugging, I always specify alert("click"), because I assumed it needed a string :) Commented Jul 23, 2011 at 18:52
  • Hum. Doesn't work on the last version of Chrome for me! Commented Jul 23, 2011 at 18:53
  • 1
    how about append($('<input type="text" onclick="alert();">')); instead? Commented Jul 23, 2011 at 18:56
  • Yep, that works. But it still puzzles me as to why my first method fails. Commented Jul 23, 2011 at 19:00

3 Answers 3

3

Why not:

$("h1").append($("<input>").attr("type","text").click(function(){alert()}));
Sign up to request clarification or add additional context in comments.

Comments

2

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');

2 Comments

@rabudde, with the exception that i explained why, and that I used a different context for appending the element.
@zzzzBov for sure, but the result is the same ;)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.