Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to a jQuery click() function

I have a simple span like so

<span class="action removeAction">Remove</span>

This span is within a table, each row has a remove span.

And then I call a URL using AJAX when that span is clicked. The AJAX event needs to know the ID of the object for that row? What is the best way of getting that ID into the click function?

I thought I could do something like this

<span class="action removeAction" id="1">Remove</span>

But an ID should not start with a number? Right? Then I thought I could do

<span class="action removeAction" id="my1">Remove</span>

Then just strip the 'my' part from the ID, but that just seems Yuk!

Below is my click event and where my AJAX event is.

<script type="text/javascript" language="text/javascript">

$(document).ready(function()
{

    $(".removeAction").click(function()
    {
        //AJAX here that needs to know the ID            
    }
});

</script>

I am sure there is a nice way of doing this?

Note: I am not looking for

$(this).attr("id");

I want to be able to pass more than one piece of information

Thanks. Jake.

like image 575
Jake N Avatar asked May 10 '10 09:05

Jake N


People also ask

How do you pass a value in Click event?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...

What is click in jQuery?

jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.


2 Answers

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>
like image 67
Mathias Bynens Avatar answered Sep 19 '22 18:09

Mathias Bynens


$(this) within your click function represents the clicked element

$(".removeAction").click(function() {
    //AJAX here that needs to know the ID
    alert($(this).attr('id'));           
}
like image 40
Flatlin3 Avatar answered Sep 21 '22 18:09

Flatlin3