Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on() click event catching dynamic 'data-' attribute in list of buttons to pass value to other function?

Tags:

I have a dynamic table list of around 40 rows each with an edit button containing a date field. I also have the following click event script trying to attach to each button via a common class which needs to access the value of a data- attribute within the button image code seen further below:

$('.showEdt').each(function () {    var $this = $(this);    $(this).on("click",$this.data('eValz'), function () {           alert(this);    });  }); 

Example of the edit buttons which are dynamically generated:

<img src="edit.png" title="edit" class="showEdt" data-evalz="(eyCKeVua/TNF117)" /> 

Problem:

The script loads ok, when the edit button is clicked the alert displays: [object HTMLImageElement] instead of the data-evalz value ??

Please provide suggestions of how I can access the data unique to the button that is clicked?

like image 787
Martin Sansone - MiOEE Avatar asked Nov 17 '13 06:11

Martin Sansone - MiOEE


People also ask

What is data() in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

How to bind the click event in jQuery?

Use the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

How to bind function in jQuery?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements. data: This is the data which can be shown over the selected elements.


1 Answers

You're not using the on function correctly. Here's one way you can do this: FIDDLE

$('.showEdt').each(function () {     var $this = $(this);     $this.on("click", function () {         alert($(this).data('evalz'));     }); }); 

Also, notice you've written eValz instead of evalz on your code. Data attributes are case-sensitive so be careful with how you write them.

like image 128
Taylan Aydinli Avatar answered Sep 28 '22 13:09

Taylan Aydinli