Get the id of the clicked link [duplicate] - javascript

This question already has answers here:
Getting the ID of the element that fired an event
(24 answers)
Closed 6 years ago.
I'd like to get the id of the clicked link with jQuery. Why does this return Undefined instead?
test = function(e) {
alert($(e).attr('id'));
return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
azeaze12
azeaze13
azeaze14

replace e with this, e refers to event object.
alert($(this).attr('id'));
or even better
$('.bleu').click(function(e) {
alert($(this).attr('id'));
return false;
})

You need to use this it refers to the clicked dom element, first parameter in click event handler is event object
test = function(e) {
alert($(this).attr('id'));
return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
azeaze12
azeaze13
azeaze14

Use this, and use .prop for id or simply this.id:
test = function(e) {
alert(this.id);
return false;
}
$('.bleu').click(test);
Alternative if the context is bound on the function, eg while binding events on Backbone views, you can use event.currentTarget, consider this:
$(el).click(function(event) {
console.log(this) // { "my": "context" }
console.log(event.currentTarget); // [DOMElement]
}.bind({
my: 'context'
}));

Use click event and use attr to get id. Try this:
$(".bleu").click(function(e) {
alert($(this).attr("id");
});

User this keyword
<script>
test = function(e) {
debugger;
alert($(this).attr('id'));
return false;
}
$('.bleu').click(test)
</script>

Related

Attach attribute [data-name] then click using this data attribute [duplicate]

This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 4 years ago.
I'm trying to add a data-name attribute on clicking one element and then when that element is clicked do something else.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("[data-name='btn02']").on("click", function() {
console.log("I clicked this button");
});
It is updating in the DOM but not working?
Any ideas?
You must use event delegation since the attribute you're using in the selector of the second click event [data-name='btn02'] is created dynamically by the JS code:
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("body").on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn01">CLICK ME then click the span bellow</button>
<br><br>
<span class="next">Next span</span>
Try the following, use event delegation for attaching event to "[data-name='btn02']", as $("[data-name='btn02']") element will not exist till $(".btn01") is clicked.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$(document).on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
If you are just trying to make it so the first button needs to be clicked before the second can, you can just use a boolean variable for that:
var firstButtonClicked = false;
$(".btn01").on("click", function() {
firstButtonClicked = true;
});
// the second button
$(".next").on("click", function() {
if (firstButtonClicked == true) {
console.log("I clicked this button after the first one");
}
});

Bind to jquery function issue

I'm using JQuery inside EcmaScript 6 class, and I have an event function which fires on instantiation of the class and the event contains different JQuery events which need to interact with the Class , so I do .bind() to achieve that, all works ok except one event which for some reason overrides this that belongs to jquery element "this" with "that" which I passed with .bind(that) method, here is my code (everything works exept for this event) :
var that = this;
$(document).on('click', '[select-file]' , function(event) {
event.preventDefault();
console.log(this);
}.bind(that));
so the console log gives me the parent class instead of jquery element
where as this works as expected:
$(document).on('click', '[open-file-dialoge]', function(event) {
event.preventDefault();
$('[file-dialoge]').modal('show');
if ($(this).attr('mitiupload') == 'false') {
// check if multiple upload is disabled
that.multiUpload = false;
$(this).removeAttr('multiple');
}
that.insertFiles();
}.bind(that));
Pleas help , I can't understand what is going on here one does not work as expected even though there is no big difference between them ;(
Function#bind() changes the context of this in a function. If you want the current element you can use event.currentTarget
var that = {};
$(document).on('click', 'button', function(event) {
event.preventDefault();
var el = event.currentTarget;
console.log('this=', this);
console.log('el=', el)
}.bind(that));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>

Get ID of Element Being Clicked and Pass as Parameter?

How does one, through jQuery, get the ID of an element that is being clicked on and then pass it as a parameter into a function? Example jQuery code below.
jQuery(document).ready(function() {
var id = this_id;
jQuery(".lightbox a").click({param: id}, functionName);
});
May I note that the "param" parameter is integral to the structure of the function.
Apologies all, I am no Javascript master by any means.
I'm guessing the point is to pass event data to a function that expects that, as ,click() supports the .click( [eventData ], handler(eventObject) ) syntax, and if so, you have to iterate the collection yourself:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).click({param: this.id}, functionName);
});
});
EDIT:
You could do this with on() as well:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
FIDDLE
Within the click handler, you can access the element ID with this.id or $(this).attr('id'):
jQuery(document).ready(function() {
jQuery(".lightbox a").click(function(){
functionName(this.id);
});
});
You can use this.id inside a click event, example:
jQuery(".lightbox a").click(function() {
var id = this.id;
//pass to a function
testFunction(id);
});
function testFunction(param) {
console.log(param);
}
It's easy just access to the this element to get the clicked element, then extract its id and save it into a variable like this:
jQuery(".lightbox a").click(function(){
var id = jQuery(this).attr("id");
callFunction(id);
});
http://jsfiddle.net/pArW6/
jQuery(document).ready(function() {
jQuery(".lightbox a").click(functionName);
});
function functionName()
{
alert(this.id);
}
You can you Use $(this).att("id").
$(".lightbox a").click(function() {
var ID=$(this).att("id");
//pass to a function
TestFunction(ID);
});
function TestFunction(P) {
console.log(P);
}
Live example
http://jsbin.com/enobop/1/edit
You can do this:
jQuery(document).ready(function () {
jQuery(".lightbox a").click(function (e) {
// Cancel the default action (navigation) of the click.
e.preventDefault();
// 'this' here refers to the link being clicked in the current scope
// you can check the console for the id for debug purpose
console.log(this.id);
// pass the id to the function
functionName(this.id);
});
});
Another way is to use the event parameter that gets passed to the callback function.
jQuery(".lightbox a").click(function(ev) {
console.log(ev.target.id);
}
Of course it's a mix of jQuery and pure JS.
Usually you have a function for an event declared with
function(event)
and the event has a target and the id of the target is, what you want. So
$("SomeElement").on("click", function(e){ callanotherFunction(e.target.id) })
does, what you wanted
You can use this.id or $(this).attr("id");, but you might want to get a reference to $(this) - wrapped or not - immediately and work from a variable if you do much of anything else in there.

alert individual attribute value [duplicate]

This question already has answers here:
Getting the ID of the element that fired an event
(24 answers)
Closed 9 years ago.
I want to identify each element by it's name attribute. Each element has the same class and will ultimately contain differing dynamic information.
For example I would want the following code to alert the individual element's name value:
html:
<p class="pexample" name="0">this is p #1</p>
<p class="pexample" name="1">this is p #2</p>
<p class="pexample" name="2">this is p #3</p>
jquery:
$('p').on('click', function() {
if ($('p').attr('name') !== undefined) {
alert($('p').attr('name'));
}
})
Here is a jsfiddle.. http://jsfiddle.net/XG7nd/1/
This code however only alerts the initial elements name value. Help is greatly appreciated.
This should do:
$('p').on('click', function() {
var name = $(this).attr('name');// `this` here refers to the current p you clicked on
if (name ) {
alert(name);
}
})
While doing $('p').attr('name') this will always give you the name of the first item in the collection.
Demo
Try this:
$(document).on('click','p', function() {
alert($(this).attr('name'));
});
DEMO
You want to use $(this)
$('p').on('click', function() {
if($(this).attr('name') !== 'undefined') {
alert($(this).attr('name'));
}
});
This is occurring because you are getting the name attribute for the first <p> on every click. You need to specify the one that the event originated from:
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Note, jQuery selectors return an array of matching elements. You must use the this keyword to get a handle on the element in the current context.
FIDDLE
Explanation
You keep looking for the p element even on click, so it'll select the first one it finds.
What your code says:
When p is clicked:
Find a p element and alert its attribute.
What you really want:
When p is clicked:
alert the clicked element's attribute
Solution
Select the attribute of this, which is the clicked element.
JSFiddle
JavaScript
$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
alert($(this).attr('name'));
}
})
Read more about the this keyword.

Confused with calling JQuery custom function

I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/

Categories