tags:

views:

38

answers:

2

I have a table with dynamically created Edit buttons. The ID of the buttons is a string that is appended with table content id.

i.e: <input id='edit'+id type='button' value='Edit' onclick=edit(this.id) />

How can i get the ID(=edit+id) value of the button using jquery.

Thanks for your replies.

Hey I am new to jquery. I understand the answers, but where i have to put those lines. In the function i called when it clicked? If so, just that one line is enough???

+3  A: 

You have to get a reference for the input element. Then, just call

reference.attr('id');

If it had a class, for example, inputClass, you could do:

var reference = $(".inputClass");

Here's how I would approach your particular situation. You have:

<input id='edit1' type='button' value='Edit' onclick=edit(this.id) />
<input id='edit2' type='button' value='Edit' onclick=edit(this.id) />
<input id='edit3' type='button' value='Edit' onclick=edit(this.id) />

I would replace this for:

<input id='edit1' type='button' value='Edit' class='inputClass'/>
<input id='edit2' type='button' value='Edit' class='inputClass'/>
<input id='edit3' type='button' value='Edit' class='inputClass'/>

Then, anywhere in your page, you write this piece of code:

$(document).ready(function() {
   $('.inputClass').each(function() {
      $(this).click(function(){
          var id = $(this).attr('id');
          //Do whatever the edit function should do with the id
      });
   });
});

this binds a function for each of the elements which call your edit function...

Rodrigo Gama
What do you mean by reference?
NooBDevelopeR
Just put an example in the edit! For more, take a look here: http://www.tequilafish.com/2007/12/04/jquery-how-to-get-the-id-of-your-current-object/
Rodrigo Gama
Hey I am new to jquery. I understand the answers, but where i have to put those lines. In the function i called when it clicked? If so, just that one line is enough???
NooBDevelopeR
Added some more code to the answer, hope it helps.
Rodrigo Gama
A: 
 var id = $("td input[type='button']").attr('id');

The selector says "The input button within a TD" or

 var id = $("td input[id^='edit']").attr('id');

The selector says "The input element with an id starting with 'edit' within a TD"

or you can go the whole way:

 var id = $("td input[type='button'][id^='edit']").attr('id');

The selector says "The input button with an id starting with 'edit' within a TD"

James Curran
Would this work if he has more than one? I believe this is the case... He probably wants to retrieve the id from inside the edit function... right, MaRaVaN?
Rodrigo Gama
@Gama: Yes Gama, You were right.
NooBDevelopeR
@Both: Hey I am new to jquery. I understand the answers, but where i have to put those lines. In the function i called when it clicked? If so, just that one line is enough???
NooBDevelopeR