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)" />
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?
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.
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" ).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With