Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trigger click an element with a specific class and attribute

I have few link elements related to a certain class and assigned row attributes to it and I'm trying to trigger click event based on the attribute value.

<a class="manage_edit_nb" nb_id="1"></a> | <a class="manage_del_nb" nb_id="1"></a>
<a class="manage_edit_nb" nb_id="2"></a> | <a class="manage_del_nb" nb_id="2"></a>
<a class="manage_edit_nb" nb_id="3"></a> | <a class="manage_del_nb" nb_id="3"></a>...

Is it possible to trigger click or any event for a certain attribute value for a certain class?

If I try something similar to

$('a[nb_id = "1"]').trigger('click');

it triggers click event for all elements irrespective of class but I failed to figure out how to put class reference in there!

like image 356
Anupam Avatar asked Feb 08 '23 05:02

Anupam


2 Answers

First, the nb_id is not a valid attribute, use data-id instead. data-* attributes are allowed, and I personally like them. And, they can be accessed using $.attr('data-id') method, and their value can bee updated using $.attr('data-id', 'new value'). Going back to the question, try using below selector

$('.manage_del_nb[data-id="1"]').get(0).click();

OR

$('.manage_edit_nb[data-id="1"]').get(0).click();

Why .get(0)? Assuming that the element has been bound with .click(callback()) or .on('click'), the .trigger('click') will not do anything, so I am using .get(0) to get the DOM object which has that method to simulate the click event. Regardless of being said, you can use trigger('click') the way you're already using

like image 151
Adam Azad Avatar answered Feb 10 '23 23:02

Adam Azad


This should work fine.

$('a.manage_edit_nb[nb_id="1"]').trigger('click');

here it is working:

https://jsfiddle.net/link2twenty/g0txnzfw/

like image 31
Andrew Bone Avatar answered Feb 10 '23 23:02

Andrew Bone