0

I'm updating a page through ajax, so I'm creating (text) buttons dynamically. I know how to set up an onclick event, but then how to I get the id of the button in the handler?

Using sinatra with ruby and jquery 1.5. Here is the partial code:

<div onclick='my_handler()' ><a><href>[Edit]</href></a></div>

and the js code:

function my_handler (){
   alert ("button id is ..." )
}

thanks

2
  • What button? I don't see any button elements in your example. Commented Feb 29, 2012 at 20:05
  • And you should brush up on your html. href isn't a tag, and your div doesn't have an id parameter Commented Feb 29, 2012 at 20:20

1 Answer 1

5
alert ("button id is " + this.id);

And since you've said you're already using jQuery, please separate your HTML and JS:

<div class="edit">

and

$('div.edit').on('click', function()
{
    alert ("button id is " + this.id);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that helps, but I'm not explaining correctly. The above solution works once, but when I reload the form, using AJAX, it no longer works. That's why I was adding the 'onclick' attribute dynamically. The 'onclick' solution works after reloads, I just don't know how to get the id. Does that make sense? My terminology may be wrong, here, I'm a newbie. Thanks for the help.
The .on() solution will work even if you dynamically build the HTML.

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.