trigger click an element with a specific class and attribute - javascript

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!

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

This should work fine.
$('a.manage_edit_nb[nb_id="1"]').trigger('click');
here it is working:
https://jsfiddle.net/link2twenty/g0txnzfw/

The thing that you are trying to do by the above code is triggering a click event on both '.manage_edit_nb' and '.manage_del_nb' selector and hence the event is occuring on both. Try to be little more specific by giving the class name like
$('a.manage_edit_nb[nb_id = "1"]').trigger('click');

I think this is exactly what you need : First of all, change all nb_id to data-nb_id. and use the following code, needs jquery.
$(document).ready(function() {
// Handle click event on the class required
$('.manage_edit_nb').click(function(){
// Get nb_id of that particular anchor event of the class
var nb_id= $(this).attr('data-nb_id');
// Switch on nb_id
switch(nb_id){
// Handle your cases separately here
case "1":
alert('Case 1');break;
case "2":
alert('Case 2');break;
case "3":
alert('Case 3');break;
}
});
});

Related

attribute starts with selector ,working for first input field(not for others)

Here i am having an issue with attribute starts with selector ,i have tried to do validation of multiple fields ,having dynamic ids ,but not succeed .
below is what i tried so far .
i have seen other suggestion in So,but unable to made it.
$("input[id^='product-unit-price-']").keydown(function (event) {
});
Html
<input type="text" class="form-control pro-input valfields" id="product-unit-price-<?php echo $id;?>" name="unit_price[]" onblur="getTotalPrice(<?php echo $id;?>)" required="">
here id is dynamic like
product-unit-price-0
product-unit-price-1
product-unit-price-2
product-unit-price-3
and so on..
here its working for only the first id (product-unit-price-0) ,but not for rests.
Its all the things.
Suggest me.
thank you.
I think you are using $("input[id^='product-unit-price-']") to refer the element inside the handler in this case while applying val() method which always return the value of the first element, not the element which is fired the event. In such case use $(this) to refer the element where this refers to the dom object of event fired element.
$("input[id^='product-unit-price-']").keydown(function (event) {
// refer element by `$(this)`
})
FYI : It's always better to provide a common class for the group of the element and select based on that which is the better way to do it.
Why you not go with class selector?
$(".form-control.pro-input.valfields").keydown(function (event) {
// your logics here
}
Because from class selector you can select set of same class group elements and apply event on each element of set.

send that specific element which is triggered by onClick function

This is my HTML :
<li class="custom-bottom-list">
<a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a>
</li>
My javascript function Upvote :
function upvote(el){
$(el+' i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
console.log( event );
}
Basically i want to select and change the css of the 'i' tag inside the particular element which is clicked.
What its doing now is its changing the css of all 'i' tags present in the page.
Can somebody tell me a efficient way to do this?
PS - I tried onClick="upvote(event) and $(event.target).removeClass('fa-thu..
But this works only when I click the 'i' tag. When i click the span tag it changes the span's css!
You can't glue different selectors like that together.
el does not contain a string selector, so you need to use the jQuery library to traverse to the i element.
If you were to console.log(el) you would see why that selector wouldn't work.
Use .find:
$(el).find('i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
Another method (although slower, and more limited because it only travels one level in the DOM):
$(el).children('i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
And, as #newboyhun pointed out, another way is to provide context to the selector:
$('i', el).removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
use find() to get child
$(el).find('i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
or you can find child using class like below
$('.fa-thumbs-o-up',el).removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
u can try children() too
$(el).children('i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
$(el).find('i').removeClass('fa-thumbs-o-up').addClass('fa-refresh fa-spin');
You can try this
if you want to custom CSS
$(el).find('i').css({'color' : 'black'});
if you want to add or remove Class
$(el).find('i').removeClass('fa-thumbs-o-up').addClass("fa-spin");

Best way to assign Jquery events to Dynamic buttons

I am generating twitter bootstrap modals dynamically based on the user action (Long Story). Lets say some times user can see 100 modals on his screen. In each and every modal I have 5 dynamic buttons, each have it own purpose and did same in all modals, and have different id's.
I am attaching onClick events to those buttons by using jquery when ever there is a new twitter modal opens up by using the button id as follows
$(document).on("click","#btn"+btnNumber, function(){
//Code Goes Gere
});
So If I open 100 modals, each have 5 buttons, Is it good idea to assigning click events for 500 times ?
or Is it good Idea to assign click events by using it's name attribute for 1 time as follows
$(document).ready(function(){
$(document).on("click","btnNameAttr", function(){
//Code Goes Gere
});
});
The jQuery on() can help you in this. First you need to detach appending DATA to your element ID like btn+btnNumber. You can add your custom information in any data-x attribute like data-custom-info and use the jQuery attr('data-custom-info') syntax to retrieve the information. The event handlers registered with on() method is also available for future elements(elements created after script execution). Like below.
When creating new button, add render it as..
<input .... class="btnWithData" data-custom-info="1" ... />
<input .... class="btnWithData" data-custom-info="2" ... />
and your event handler goes like..
$(document).ready(function(){
$('body').on('click','.btnWithData',function(){
//DO WHATEVER
var buttonData=$(this).attr('data-custom-info');
//DO WHATEVER
});
});
You should assign delegated event listeners using jQuery.on() method as #Ananthan-Unni suggests, but in the form:
$.on('click', 'button', listener)
In this case you do not need to assign unique ids or attributes. You can use tag name or class name as a selector (2nd argument).
Have a look here: https://api.jquery.com/on/ and read on delegated events.
Best is don't use closures they require memory. Rely on good old data tags, instead:
$(document).ready(function () {
$("#wrapper").on("click", "btnNameAttr", function () {
var n;
n = $(this).data("number");
// code goes here
});
});
To differentiate the actually clicked element inside #wrapper you use data-number attributes like this:
<div id="wrapper">
<img data-number="000" />
<img data-number="001" />
<img data-number="002" />
<img data-number="003" />
</div>
This code will perform much better and you can still have all functionality you want by using wrapping <div> elements and data-number="" attributes. And you don't interfere with class or id attributes you might already have on those elements.
You can even add the command to the tag:
<img data-number="000" data-command="edit" />
<img data-number="000" data-command="show" />
<img data-number="000" data-command="delete" />
And switch on it:
switch ($(this).data("command"))
{
case "edit":
// edit element with number n here
break;
}

How to select element relative to 'this' in javascript

I have the following:
<div class="tab-pane" id="message">
<textarea rows="4" cols="50" id="send_message" placeholder="Enter text ..."> </textarea>
OK
Cancel
I want to bind the click method to the 'div' element , and when one of the child 'a' elements is clicked do separate things. I am trying to distinguish between them using the button text, but the following is not working:
$(function(){
$('#message').click(function(){
if($(this + ">a").is(":contains(OK)")) {
console.log("OK!!");
How can I fix this?
Okay there are two ways of doing this:
.find(selector)
if(this).find("a").is(":contains(OK)")) {
console.log("OK!!");
OR
$(selector,context)
if("a",this).is(":contains(OK)")) {
console.log("OK!!");
In javascript, this is essentially the context of the current function. In jQuery event callbacks, this is set to be the source element of the event - not the selector string, which is what you are treating it as.
Instead, you want to do a test like: if($("a", this).is(":contains(OK)")) {
This works because the second parameter to the jQuery selector is the context to search in, so you are only searching for the a tags under the source element of the click.
Binding the click element to the Div, then checking the text string of the A tags will make both events happen on every click. You want to bind 2 separate click events on each A tag. Add an ID to each A tag, then try this code
$('#okLinkID').click(function(){
console.log("OK!!");
});
$('#cancelLinkID').click(function(){
console.log("Cancel!!");
});
//Attaches only one listener to the #message div and listens for any 'a' element within it to be clicked.
$('a','#message').on('click',function(){
var $this = $(this),
btnText = $this.text();
console.log(btnText);
});
http://jsfiddle.net/YA7Ds/

JQuery click listener for class

I have a class of images in HTML, with IDs img1,img2,...,img9. I want to make links (HTML a tag) with IDs link_img1, link_img2, ..., link_img9 so that whenever I click on a link, the corresponding image appears.
I'm thinking about assigning all the links to the same class, then add a JQuery click listener for that class, and inside the listener, look for the ID of that link, and shows the corresponding image. How do I add a JQuery listener for a class, and how do I get the ID from the element?
You shouldn't use the ids of a tags to define their target.
Better use the href attribute instead:
<img id="img1" ...>
<img id="img2" ...>
Click me
Click me
jQuery("a.image-link").click(function(){
$(this.href).show();
});
This allows you to have two links for the same image.
Try:
$('a.yourClassName').click(function(){
$('img#'+ this.id).show();
});
To add a listener for a class, just select it the jQuery way (i.e. $('elem.class'). Then use attr() to get the id.
Here. As mentioned in some other answers, id is probably not the best way to determine what action you should take. Use another attribute as you see fit
$('a.some-class').click(function() {
switch (this.id) {
case 'one':
// do something
break;
case 'two':
// do something
break;
default:
// do something
break;
}
});
try this
$('a.yourClass').click(function(){
var $linkID= $(this).attr('id');
$('img#'+ $linkID).show();
});

Categories