jQuery click event custom attribute undefined - javascript

I've some buttons on my page. The mockup looks like this
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>
The goal is to get the value of the data-id attribute. Currently I'm using this javascript.
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(this).attr('data-id');
});
My problem is that when I log the value to my browser console console.log(id); I the value of the id variable is undefined.
What is wrong with my code?

Using arrow function expression implies the value of this is not the one you intend.
In this case you need to use event.target:
jQuery('.js-category-delete').on('click', (event) => {
let id = jQuery(event.target).attr('data-id');
console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="js-category-delete" data-id="1">
Delete
</button>

To suggest you an alternative way:
$('.js-category-delete').on('click', function (event) {
const clickedItem = jQuery(this); // and also jQuery(event.target)
const id = clickedItem.data('id');
console.log(id);
});
The function keyword makes this what you've expected at first.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Pen: https://codepen.io/shifu462/pen/WVaGLB
Also, as a shortcut for
jQuery(event.target).attr('data-id');
I've used here another jQuery method to get the value of a data attribute.
jQuery(event.target).data('id');
Docs: https://api.jquery.com/data/

Related

Return the data-football attribute name

If I have the following piece of code:
<button id="btnOne" data-football="Mitre">Press Me</button>
How would I get the name of the data tag, so in this case it would be 'data-football'. I know how I would get the value but would like to know how I can get the name of the data-tag - in this case data-football when the button is pressed.
i.e,
$(document).on("click", "button", function(){
// Get the name of the attribute (data-football - not the value);
});
Thanks.
You can use attributes property for getting the all attributes of a HTML tag
<div id="_id" data-football='test'></div>
<script>
const attrs = document.getElementById('_id').attributes
const keyName = attrs[1].nodeName // will be data-football
</script>
Try one of the following.
$(document).on("click", "button", function(){
$(this).data('data-football')
});
Or
$(document).on("click", "#btnOne", function(){
$(this).data('data-football')
});
Read More about jQuery data

get id of button by clicked with function

html
<button id="test1" onclick="getclickname(); return false;">click</button>
javascript (it's showing "Undefined")
function getclickname()
{
alert(this.id);
}
i dont want code like this
<button id="test1" onclick="alert(this.id);">click</button>
call getclickname is needed, thanks guys
You have to pass corresponding argument to the function.
You need to pass button object to onclick function to get the id of button.
function getclickname(obj)
{
//By passing object as argument you can access all properties of that element
alert(obj.id);
alert(obj.className);
}
<button id="test1" onclick="getclickname(this); return false;" class="test_1">click</button>
You can directly pass this.id as well as an argument
function getclickname(id) {
alert(id);
}
<button id="test1" onclick="getclickname(this.id); return false;">click</button>
Note:
A bit code modification is instead of return false; you can add return before function name and that will do the same thing. like :- onclick="return getclickname(this.id);"
By passing object as argument you can access all properties of that element (check first code sample modification).
Hope this Helpful...
view
onclick="return getclickname(this);"
js
function getclickname(these)
{
alert(these.id);
}
Please try the below code. It's working for you.
Use class for click event in button.
<button id="test1" class="test-btn" >click</button>
Use the below click event function to get id after click.
$('.test-btn').click(function() {
var id = $(this).attr('id');
alert(id)
});
Use like this
<button id="test1" onclick="getclickname(this); return false;">click</button>
<script>
function getclickname(e)
{
alert(e.id);
}
</script>

How to access data attribute value in jquery (cash-dom)?

I use webpack and the data-cash. I have a link with data attribute that I want to access.
HTML:
<a class="myBtn" data-article="some value">
<div>some text here</div>
</div>
Javascript:
$('.myBtn').on('click', (e) => {
const articleData = $(e.currentTarget);
console.log(articleData);
modal.style.display = 'block';
e.preventDefault();
});
The code above returns
Cash [a.myBtn]
How can I access the value of data attribute (article)?
Try with $(this).data('article') inside your event listener. jQuery has a .data() function for those purposes.
EDIT: Attached a Fiddle.
For cash-dom jQuery you should use .attr() instead of .data(). According to their docs you can get your data-article attribute by doing $(element).attr('data-article').
My solution looks like this:
$('.myBtn').on('click', (e) => {
const articleData = $(e.currentTarget);
articleData.attr('data-article')
console.log(articleData.attr('data-article'));
e.preventDefault();
});

Pass clicked element' s attributes in another function

Hello guys I try to figure out how can I pass an element's attributes which I clicked in a different function
To be specific I have a dozen of elements with the same className = online
However each of the elements has one unique id which I assigned to them dynamically.
I use $(document).on because I want to listen on the document, for a click because the elements with className=online are created dynamically too.
$(document).on("click", ".online", isInPrivateChat);
How can I then in a different function for example
function TakeTheidfTheElement(){
//take the id of the element i clicked
}
I know I should use jquery method .attr('id') but cant really make it work.
Thanks
Working fiddle.
You could simply get the id from the callback function isInPrivateChat using this.id like :
function isInPrivateChat(){
alert( this.id );
}
Hope this helps.
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(){
console.log( this.id );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='online' id='id_1'>Btn 1</button>
<button class='online' id='id_2'>Btn 2</button>
<button class='online' id='id_3'>Btn 3</button>
Carry the ID through:
$(document).on("click", ".online", function() {
isInPrivateChat($(this).attr('id')); /* <-- get id and pass it in */
});
then
function TakeTheidfTheElement(idPassed){
// do something with idPassed
}
For the record, Zacaria's answer is the better option - showing this is how you can use .attr('id')
You can pass the whole element to a sub function and there you can use JQuery or straight javascript to get the properties of the element.
$(document).on("click",".online",function() {
getMyId(this);
});
function getMyId(element) {
alert(element.id);
}
If you just wanted to pass the id through to the sub function you can do:
$(document).on("click",".online",function() {
getMyId(this.id);
});
function getMyId(elementID) {
alert(elementID);
}
Here's a fiddle of it working
check the below code snippet
$(document).on("click", ".online", isInPrivateChat);
function isInPrivateChat(event) {
anotherFunctin(event.currentTarget.id);
}
function anotherFunctin(id){
console.log(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="online" id="id">
click me
</div>

Passing data to a click listener

I have a button in my html that when clicked, I need it to pass the index attribute value to my click listener:
<button class="btn buy-button js-prevent-cart-listener guys" index="1">Add To Cart</button>
and the listener:
$('.girls').on('click', buyButtonGirlsClickHandler, index);
So that when I run this function, I can access the event value and use it within the function:
function buyButtonClickHandler(evt) {
console.log(evt.value);
}
I dont want to change it to have an 'onclick()' attached to the button. Is this possible and if so how? Obviously the code above is not able to pass the index value, and i have tried numerous times
You need not to pass the index in on function. You should try changing your on function to
$('.girls').on('click', buyButtonGirlsClickHandler);
and in the handler you can receive it by attr
function buyButtonClickHandler(evt) {
console.log(evt.value);
var index= $(event.target).attr("index");
}
https://jsfiddle.net/525npjfn/
or as #Andreas commented , use this inside click.
function buyButtonGirlsClickHandler(evt) {
console.log(evt.value);
var index = this.getAttribute("index");
alert(index);
}
https://jsfiddle.net/525npjfn/2/
On button click, you can store it's index value in a variable and then pass it into the desired function. This is the clean snippet to solve your problem.
Please use data- prefix to use custom HTML attribute otherwise HTML validators will cry for this.
$(document).ready(function() {
$('.js-prevent-cart-listener').click(function() {
var idx = $(this).attr('data-index');
buyButtonClickHandler(idx);
})
});
function buyButtonClickHandler(idx) {
console.log("This is index value " + idx);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn buy-button js-prevent-cart-listener guys" data-index="1">Add To Cart</button>
Instead of passing the event handler directly, wrap it inside a new function. Your index data will be passed because it stays in the scope.
let index = "whatever your index data is";
$('.girls').on('click', (e, index) => buyButtonGirlsClickHandler(e, index) );
Note: I'm using ES6 syntax there, may not work on old browsers.

Categories