I have a simple span like so
Remove
This span is within a table, each row has a remo
If you insist on using old-school HTML 4.01 or XHTML:
$('.removeAction').click(function() {
// Don’t do anything crazy like `$(this).attr('id')`.
// You can get the `id` attribute value by simply accessing the property:
this.id;
// If you’re prefixing it with 'my' to validate as HTML 4.01, you can get just the ID like this:
this.id.replace('my', '');
});
By the way, in HTML5, the id attribute can start with a number or even be a number.
Then again, if you’re using HTML5 anyway, you’re probably better off using custom data attributes, like so:
<span class="action removeAction" data-id="1">Remove</span>
You could have a hidden field on each row which stores the ID and/or other data needed in a JSON object & use that instead of hacking around with the span tag.
<tr>
<td>
<span class="action removeAction">Remove</span>
<input type="hidden" value="1" />
</td>
</tr>
$('.removeAction').click(function(){
var id = $(this).next().val();
// do something...
});
HTH
The following code will get you the ID of the clicked span
. Using the ID isn't perfect, but it will work.
$(".removeAction").click(function() {
alert($(this).attr("id"));
});
You could try jQuery.data(): http://api.jquery.com/jQuery.data , but that would mean server-side generated js code to execute when the page loads so that you can store the ids for later reuse (your remove action)
// this part would have to be server 'generated'
// and by that I'm referring to the '<?=$row_id?>'
$('table .remove').each(function(){
var MyElem = $(this);
MyElem.data('id', <?=$row_id?> );
MyElem.click(function(){
the_id = $(this).data('id');
// ajax call goes here
});
});
$(this) within your click function represents the clicked element
$(".removeAction").click(function() {
//AJAX here that needs to know the ID
alert($(this).attr('id'));
}