jQuery on-click event empty
I'm trying to read an attribute in my JavaScript-Function, so I can then further call a DELETE via AJAX with this attribute, but I already fail with retrieving the attribute by, what appears to me as, random. (jQuery version used for that is 3.2.1)
The "button" to start that chain (also already tried without the href
and with href="#"
):
UPDATE: Since it appeared as a comment, I indeed have something within the a
-tag
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash"></i>
</a>
My JavaScript:
$(document).ready(function(){
$('.delete-record').on('click', function(e){
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
During testing with the confirm, I found out that my ID is sometimes set to undefined
. Sadly I have no clue how this sometimes works and shows me the ID, and sometimes not.
Is there a solution to make this work with every click and not only about 24 out of the 42?
javascript jquery
add a comment |
I'm trying to read an attribute in my JavaScript-Function, so I can then further call a DELETE via AJAX with this attribute, but I already fail with retrieving the attribute by, what appears to me as, random. (jQuery version used for that is 3.2.1)
The "button" to start that chain (also already tried without the href
and with href="#"
):
UPDATE: Since it appeared as a comment, I indeed have something within the a
-tag
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash"></i>
</a>
My JavaScript:
$(document).ready(function(){
$('.delete-record').on('click', function(e){
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
During testing with the confirm, I found out that my ID is sometimes set to undefined
. Sadly I have no clue how this sometimes works and shows me the ID, and sometimes not.
Is there a solution to make this work with every click and not only about 24 out of the 42?
javascript jquery
1
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20
add a comment |
I'm trying to read an attribute in my JavaScript-Function, so I can then further call a DELETE via AJAX with this attribute, but I already fail with retrieving the attribute by, what appears to me as, random. (jQuery version used for that is 3.2.1)
The "button" to start that chain (also already tried without the href
and with href="#"
):
UPDATE: Since it appeared as a comment, I indeed have something within the a
-tag
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash"></i>
</a>
My JavaScript:
$(document).ready(function(){
$('.delete-record').on('click', function(e){
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
During testing with the confirm, I found out that my ID is sometimes set to undefined
. Sadly I have no clue how this sometimes works and shows me the ID, and sometimes not.
Is there a solution to make this work with every click and not only about 24 out of the 42?
javascript jquery
I'm trying to read an attribute in my JavaScript-Function, so I can then further call a DELETE via AJAX with this attribute, but I already fail with retrieving the attribute by, what appears to me as, random. (jQuery version used for that is 3.2.1)
The "button" to start that chain (also already tried without the href
and with href="#"
):
UPDATE: Since it appeared as a comment, I indeed have something within the a
-tag
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash"></i>
</a>
My JavaScript:
$(document).ready(function(){
$('.delete-record').on('click', function(e){
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
During testing with the confirm, I found out that my ID is sometimes set to undefined
. Sadly I have no clue how this sometimes works and shows me the ID, and sometimes not.
Is there a solution to make this work with every click and not only about 24 out of the 42?
javascript jquery
javascript jquery
edited Dec 28 '18 at 11:32
ceekay
asked Dec 28 '18 at 11:10
ceekayceekay
434313
434313
1
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20
add a comment |
1
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20
1
1
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20
add a comment |
10 Answers
10
active
oldest
votes
The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.
So the solution is to either:
1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a>
clickable without also clicking the <i>
.
2) Or check for which node was clicked inside the event:
var $target = $(e.target);
var id = $target.prop('tagName') === 'I'
? $target.parent().attr('data-id')
: $target.attr('data-id');
if (!id ) {
console.error( $target );
throw new Error( 'cannot find the correct id for target' );
}
else {
var is_correct_id = confirm( 'Entry with ID ' + id );
if ( is_correct_id ) {
//createAjaxCall( 'DELETE', 'somePath', id );
}
}
There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' )
up to the implementer.
3) Or as you demonstrate, duplicate the id onto the icon. :)
add a comment |
The answer is actually based on Shilly's comment to the question.
Since I indeed got another element within my a
-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i
-tag as well:
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>
add a comment |
Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this
<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
$('#deleteButton').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
add a comment |
You should change your JS + HTML to this:
HTML
<button class="btn btn-light delete-record"
data-id="5c25f547d42"
title="Delete">
Click me!
</button>
Your problem with using <a>
is that you don't stop the defaul behaviour of the <a>
tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.
jQuery
jQuery(document).ready(function($)
{
$('.delete-record').click(function()
{
let id = $(this).attr('data-id');
if (confirm('Entry with ID '+ id)) {
//whatever
}
});
})
You don't need to get the target, just use $(this)
to get the clicked element's data-attribute. Then carry on script as normal
add a comment |
You could try specifying the role of the anchor tag to button
. Then you won't have to worry about specifying the href
as the anchor tag will be treated as button.
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
add a comment |
Use event.preventDefault()
as first line in your callback function for "click" or you'll be redirected to link or just reloaded.
add a comment |
<a class="btn btn-light delete-record" id="btnDelete" title="Delete">
$(document).ready(function(){
$('#btnDelete').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Or you can try
<a class="btn btn-light delete-record" id="btnDelete" href="javascript:DeleteRecord()" title="Delete">
<script>
function DeleteRecord(){
//Do your code here
}
</script>
add a comment |
Since you are tracking the click you should prevent the default behaviour of the click, so do like this:
$('.delete-record').on('click', function(e){
e.preventDefault();
(...)
});
you don't need to use the target, you can get the data attribute directly.
if you want to use a vanilla js approach:
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
Personally i had some problems with data attributes and jQuery so i try to avoid using jquery for that. So you can use this and use the ajax call with the id on the variable.
add a comment |
Have a look on my example, it should cover your problem:
$(document).ready(function(){
// assuming you're adding/removing .delete-record elements you should bind click on body
$('body').on('click', '.delete-record', function(e){
e.preventDefault(); // prevent default action
var id = $(this).attr('data-id') || false; // i removed $target, you don't need it
if( id !== false ){ // if id exists
if(confirm('Entry with ID ' + id){
//AJAX
}
}else{ console.log('id is invalid', id, typeof id); }
});
});
add a comment |
Use jQuery .data()
function:
<a class="btn btn-light delete-record"
href=""
data-id="5c25f547d42"
title="Delete">
Delete
</a>
$(document).ready(function () {
$('.delete-record').on('click', function (e) {
$target = $(e.target);
var id = $target.data('id');
if (confirm('Entry with ID ' + id)) {
// AJAX
}
});
});
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53957588%2fjquery-on-click-event-empty%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.
So the solution is to either:
1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a>
clickable without also clicking the <i>
.
2) Or check for which node was clicked inside the event:
var $target = $(e.target);
var id = $target.prop('tagName') === 'I'
? $target.parent().attr('data-id')
: $target.attr('data-id');
if (!id ) {
console.error( $target );
throw new Error( 'cannot find the correct id for target' );
}
else {
var is_correct_id = confirm( 'Entry with ID ' + id );
if ( is_correct_id ) {
//createAjaxCall( 'DELETE', 'somePath', id );
}
}
There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' )
up to the implementer.
3) Or as you demonstrate, duplicate the id onto the icon. :)
add a comment |
The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.
So the solution is to either:
1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a>
clickable without also clicking the <i>
.
2) Or check for which node was clicked inside the event:
var $target = $(e.target);
var id = $target.prop('tagName') === 'I'
? $target.parent().attr('data-id')
: $target.attr('data-id');
if (!id ) {
console.error( $target );
throw new Error( 'cannot find the correct id for target' );
}
else {
var is_correct_id = confirm( 'Entry with ID ' + id );
if ( is_correct_id ) {
//createAjaxCall( 'DELETE', 'somePath', id );
}
}
There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' )
up to the implementer.
3) Or as you demonstrate, duplicate the id onto the icon. :)
add a comment |
The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.
So the solution is to either:
1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a>
clickable without also clicking the <i>
.
2) Or check for which node was clicked inside the event:
var $target = $(e.target);
var id = $target.prop('tagName') === 'I'
? $target.parent().attr('data-id')
: $target.attr('data-id');
if (!id ) {
console.error( $target );
throw new Error( 'cannot find the correct id for target' );
}
else {
var is_correct_id = confirm( 'Entry with ID ' + id );
if ( is_correct_id ) {
//createAjaxCall( 'DELETE', 'somePath', id );
}
}
There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' )
up to the implementer.
3) Or as you demonstrate, duplicate the id onto the icon. :)
The issue is that when you click the icon inside the hyperlink, that the event bubbles up to the click handler. Inside the click handler, event.target will then refer to the icon element, which does not have the data-id attribute.
So the solution is to either:
1) Move the click event onto the icon and then make sure the hyperlink does not have any padding or other CSS styles that make the <a>
clickable without also clicking the <i>
.
2) Or check for which node was clicked inside the event:
var $target = $(e.target);
var id = $target.prop('tagName') === 'I'
? $target.parent().attr('data-id')
: $target.attr('data-id');
if (!id ) {
console.error( $target );
throw new Error( 'cannot find the correct id for target' );
}
else {
var is_correct_id = confirm( 'Entry with ID ' + id );
if ( is_correct_id ) {
//createAjaxCall( 'DELETE', 'somePath', id );
}
}
There are other methods to find the correct parent element, in case one day you change the structure and the icon is not an immediate child of the hyperlink anymore. But I don't use JQuery anymore, so I'll leave searching for the correct syntax for .findParent( 'a[data-id]' )
up to the implementer.
3) Or as you demonstrate, duplicate the id onto the icon. :)
answered Dec 28 '18 at 12:26
ShillyShilly
5,3781616
5,3781616
add a comment |
add a comment |
The answer is actually based on Shilly's comment to the question.
Since I indeed got another element within my a
-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i
-tag as well:
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>
add a comment |
The answer is actually based on Shilly's comment to the question.
Since I indeed got another element within my a
-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i
-tag as well:
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>
add a comment |
The answer is actually based on Shilly's comment to the question.
Since I indeed got another element within my a
-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i
-tag as well:
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>
The answer is actually based on Shilly's comment to the question.
Since I indeed got another element within my a
-tag, the target was different depending on where I clicked the link/button. As an easy fix for that, I simply appended the ID to the i
-tag as well:
<a class="btn btn-light delete-record" href="" data-id="5c25f547d42" title="Delete">
<i class="fa fa-trash" data-id="5c25f547d42"></i>
</a>
answered Dec 28 '18 at 12:22
ceekayceekay
434313
434313
add a comment |
add a comment |
Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this
<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
$('#deleteButton').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
add a comment |
Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this
<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
$('#deleteButton').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
add a comment |
Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this
<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
$('#deleteButton').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Did you tried to href="javascript" and also this could return list of elements so try to put the listener using an id like this
<a class="btn btn-light delete-record" id="deleteButton" href="" data-id="5c25f547d42" title="Delete">
$(document).ready(function(){
$('#deleteButton').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
answered Dec 28 '18 at 11:15
Mateus FreireMateus Freire
11
11
add a comment |
add a comment |
You should change your JS + HTML to this:
HTML
<button class="btn btn-light delete-record"
data-id="5c25f547d42"
title="Delete">
Click me!
</button>
Your problem with using <a>
is that you don't stop the defaul behaviour of the <a>
tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.
jQuery
jQuery(document).ready(function($)
{
$('.delete-record').click(function()
{
let id = $(this).attr('data-id');
if (confirm('Entry with ID '+ id)) {
//whatever
}
});
})
You don't need to get the target, just use $(this)
to get the clicked element's data-attribute. Then carry on script as normal
add a comment |
You should change your JS + HTML to this:
HTML
<button class="btn btn-light delete-record"
data-id="5c25f547d42"
title="Delete">
Click me!
</button>
Your problem with using <a>
is that you don't stop the defaul behaviour of the <a>
tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.
jQuery
jQuery(document).ready(function($)
{
$('.delete-record').click(function()
{
let id = $(this).attr('data-id');
if (confirm('Entry with ID '+ id)) {
//whatever
}
});
})
You don't need to get the target, just use $(this)
to get the clicked element's data-attribute. Then carry on script as normal
add a comment |
You should change your JS + HTML to this:
HTML
<button class="btn btn-light delete-record"
data-id="5c25f547d42"
title="Delete">
Click me!
</button>
Your problem with using <a>
is that you don't stop the defaul behaviour of the <a>
tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.
jQuery
jQuery(document).ready(function($)
{
$('.delete-record').click(function()
{
let id = $(this).attr('data-id');
if (confirm('Entry with ID '+ id)) {
//whatever
}
});
})
You don't need to get the target, just use $(this)
to get the clicked element's data-attribute. Then carry on script as normal
You should change your JS + HTML to this:
HTML
<button class="btn btn-light delete-record"
data-id="5c25f547d42"
title="Delete">
Click me!
</button>
Your problem with using <a>
is that you don't stop the defaul behaviour of the <a>
tag - which is a link. It's just refreshing the page (if you leave href blank). Changing it to a button is much better, as it's .. well a button in principle.
jQuery
jQuery(document).ready(function($)
{
$('.delete-record').click(function()
{
let id = $(this).attr('data-id');
if (confirm('Entry with ID '+ id)) {
//whatever
}
});
})
You don't need to get the target, just use $(this)
to get the clicked element's data-attribute. Then carry on script as normal
answered Dec 28 '18 at 11:17
treyBaketreyBake
3,0643832
3,0643832
add a comment |
add a comment |
You could try specifying the role of the anchor tag to button
. Then you won't have to worry about specifying the href
as the anchor tag will be treated as button.
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
add a comment |
You could try specifying the role of the anchor tag to button
. Then you won't have to worry about specifying the href
as the anchor tag will be treated as button.
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
add a comment |
You could try specifying the role of the anchor tag to button
. Then you won't have to worry about specifying the href
as the anchor tag will be treated as button.
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
You could try specifying the role of the anchor tag to button
. Then you won't have to worry about specifying the href
as the anchor tag will be treated as button.
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
answered Dec 28 '18 at 11:17
shellophobiashellophobia
1
1
add a comment |
add a comment |
Use event.preventDefault()
as first line in your callback function for "click" or you'll be redirected to link or just reloaded.
add a comment |
Use event.preventDefault()
as first line in your callback function for "click" or you'll be redirected to link or just reloaded.
add a comment |
Use event.preventDefault()
as first line in your callback function for "click" or you'll be redirected to link or just reloaded.
Use event.preventDefault()
as first line in your callback function for "click" or you'll be redirected to link or just reloaded.
answered Dec 28 '18 at 11:18
KalixKalix
234
234
add a comment |
add a comment |
<a class="btn btn-light delete-record" id="btnDelete" title="Delete">
$(document).ready(function(){
$('#btnDelete').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Or you can try
<a class="btn btn-light delete-record" id="btnDelete" href="javascript:DeleteRecord()" title="Delete">
<script>
function DeleteRecord(){
//Do your code here
}
</script>
add a comment |
<a class="btn btn-light delete-record" id="btnDelete" title="Delete">
$(document).ready(function(){
$('#btnDelete').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Or you can try
<a class="btn btn-light delete-record" id="btnDelete" href="javascript:DeleteRecord()" title="Delete">
<script>
function DeleteRecord(){
//Do your code here
}
</script>
add a comment |
<a class="btn btn-light delete-record" id="btnDelete" title="Delete">
$(document).ready(function(){
$('#btnDelete').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Or you can try
<a class="btn btn-light delete-record" id="btnDelete" href="javascript:DeleteRecord()" title="Delete">
<script>
function DeleteRecord(){
//Do your code here
}
</script>
<a class="btn btn-light delete-record" id="btnDelete" title="Delete">
$(document).ready(function(){
$('#btnDelete').on('click', function(e){
e.stopPropagation();
$target = $(e.target);
var id = $target.attr('data-id');
if(confirm('Entry with ID ' + id){
//AJAX
}
});
});
Or you can try
<a class="btn btn-light delete-record" id="btnDelete" href="javascript:DeleteRecord()" title="Delete">
<script>
function DeleteRecord(){
//Do your code here
}
</script>
answered Dec 28 '18 at 11:24
Neel DarjiNeel Darji
63111
63111
add a comment |
add a comment |
Since you are tracking the click you should prevent the default behaviour of the click, so do like this:
$('.delete-record').on('click', function(e){
e.preventDefault();
(...)
});
you don't need to use the target, you can get the data attribute directly.
if you want to use a vanilla js approach:
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
Personally i had some problems with data attributes and jQuery so i try to avoid using jquery for that. So you can use this and use the ajax call with the id on the variable.
add a comment |
Since you are tracking the click you should prevent the default behaviour of the click, so do like this:
$('.delete-record').on('click', function(e){
e.preventDefault();
(...)
});
you don't need to use the target, you can get the data attribute directly.
if you want to use a vanilla js approach:
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
Personally i had some problems with data attributes and jQuery so i try to avoid using jquery for that. So you can use this and use the ajax call with the id on the variable.
add a comment |
Since you are tracking the click you should prevent the default behaviour of the click, so do like this:
$('.delete-record').on('click', function(e){
e.preventDefault();
(...)
});
you don't need to use the target, you can get the data attribute directly.
if you want to use a vanilla js approach:
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
Personally i had some problems with data attributes and jQuery so i try to avoid using jquery for that. So you can use this and use the ajax call with the id on the variable.
Since you are tracking the click you should prevent the default behaviour of the click, so do like this:
$('.delete-record').on('click', function(e){
e.preventDefault();
(...)
});
you don't need to use the target, you can get the data attribute directly.
if you want to use a vanilla js approach:
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
Personally i had some problems with data attributes and jQuery so i try to avoid using jquery for that. So you can use this and use the ajax call with the id on the variable.
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
document.addEventListener("DOMContentLoaded", function () {
//const records = document.querySelectorAll('.delete-record');
Array.from(document.querySelectorAll('.delete-record')).forEach(elem =>{
elem.addEventListener('click', function(e){
//don't do the default link behaviour
e.preventDefault();
const id = this.dataset.id;
console.log('Entry with ID :' + id);
//use your jquery here
});
})
});
<a class="btn btn-light delete-record" href="" data-id="5c215f547d42" title="Delete">link1</a>
<a class="btn btn-light delete-record" href="" data-id="eeee5c1125f547d42" title="Delete">link2</a>
<a class="btn btn-light delete-record" href="" data-id="cccc5c25f431547d42" title="Delete">link3</a>
<a class="btn btn-light delete-record" href="" data-id="bbbbb5c2345f547d42" title="Delete">link4</a>
<a class="btn btn-light delete-record" href="" data-id="111115c25f547d42" title="Delete">link5</a>
answered Dec 28 '18 at 11:29
José MoreiraJosé Moreira
627
627
add a comment |
add a comment |
Have a look on my example, it should cover your problem:
$(document).ready(function(){
// assuming you're adding/removing .delete-record elements you should bind click on body
$('body').on('click', '.delete-record', function(e){
e.preventDefault(); // prevent default action
var id = $(this).attr('data-id') || false; // i removed $target, you don't need it
if( id !== false ){ // if id exists
if(confirm('Entry with ID ' + id){
//AJAX
}
}else{ console.log('id is invalid', id, typeof id); }
});
});
add a comment |
Have a look on my example, it should cover your problem:
$(document).ready(function(){
// assuming you're adding/removing .delete-record elements you should bind click on body
$('body').on('click', '.delete-record', function(e){
e.preventDefault(); // prevent default action
var id = $(this).attr('data-id') || false; // i removed $target, you don't need it
if( id !== false ){ // if id exists
if(confirm('Entry with ID ' + id){
//AJAX
}
}else{ console.log('id is invalid', id, typeof id); }
});
});
add a comment |
Have a look on my example, it should cover your problem:
$(document).ready(function(){
// assuming you're adding/removing .delete-record elements you should bind click on body
$('body').on('click', '.delete-record', function(e){
e.preventDefault(); // prevent default action
var id = $(this).attr('data-id') || false; // i removed $target, you don't need it
if( id !== false ){ // if id exists
if(confirm('Entry with ID ' + id){
//AJAX
}
}else{ console.log('id is invalid', id, typeof id); }
});
});
Have a look on my example, it should cover your problem:
$(document).ready(function(){
// assuming you're adding/removing .delete-record elements you should bind click on body
$('body').on('click', '.delete-record', function(e){
e.preventDefault(); // prevent default action
var id = $(this).attr('data-id') || false; // i removed $target, you don't need it
if( id !== false ){ // if id exists
if(confirm('Entry with ID ' + id){
//AJAX
}
}else{ console.log('id is invalid', id, typeof id); }
});
});
answered Dec 28 '18 at 11:32
darklightcodedarklightcode
1,25689
1,25689
add a comment |
add a comment |
Use jQuery .data()
function:
<a class="btn btn-light delete-record"
href=""
data-id="5c25f547d42"
title="Delete">
Delete
</a>
$(document).ready(function () {
$('.delete-record').on('click', function (e) {
$target = $(e.target);
var id = $target.data('id');
if (confirm('Entry with ID ' + id)) {
// AJAX
}
});
});
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
add a comment |
Use jQuery .data()
function:
<a class="btn btn-light delete-record"
href=""
data-id="5c25f547d42"
title="Delete">
Delete
</a>
$(document).ready(function () {
$('.delete-record').on('click', function (e) {
$target = $(e.target);
var id = $target.data('id');
if (confirm('Entry with ID ' + id)) {
// AJAX
}
});
});
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
add a comment |
Use jQuery .data()
function:
<a class="btn btn-light delete-record"
href=""
data-id="5c25f547d42"
title="Delete">
Delete
</a>
$(document).ready(function () {
$('.delete-record').on('click', function (e) {
$target = $(e.target);
var id = $target.data('id');
if (confirm('Entry with ID ' + id)) {
// AJAX
}
});
});
Use jQuery .data()
function:
<a class="btn btn-light delete-record"
href=""
data-id="5c25f547d42"
title="Delete">
Delete
</a>
$(document).ready(function () {
$('.delete-record').on('click', function (e) {
$target = $(e.target);
var id = $target.data('id');
if (confirm('Entry with ID ' + id)) {
// AJAX
}
});
});
answered Dec 28 '18 at 11:40
Alibek KaparovAlibek Kaparov
347
347
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
add a comment |
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Thanks. I already tried the data function vs. the attr, but it also didn't work. Besides that from different other solutions here on so (e.g. stackoverflow.com/questions/7261619/jquery-data-vs-attr) there should be no real difference for my kind of problem
– ceekay
Dec 28 '18 at 11:44
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
Dude, I just copied and changed some parts of your code and it work, but open dev tools, confirm dosen't work on playgrounds. [here is example] (codepen.io/anon/pen/GPMZZx?editors=1010)
– Alibek Kaparov
Dec 28 '18 at 11:53
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53957588%2fjquery-on-click-event-empty%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Is there anything inside the hyperlink? Clicking a different element inside the <a> tag will set the e.target to that element instead of the parent link and hence, will not find the data-id attribute. For the record, you can style buttons as well; using hyperlinks for other things than navigating to a different page can cause issues, since the default behaviour of a hyperlink is to change the web page.
– Shilly
Dec 28 '18 at 11:16
If it's undefined, you would have gotten some console errors - could you please post any errors you may have received?
– Jack Bashford
Dec 28 '18 at 11:18
Why do you declare the $target as global variable? Make it a local variable and try again?
– Zhao Hainan
Dec 28 '18 at 11:19
@JackBashford Sadly no (console) errors to work with :/
– ceekay
Dec 28 '18 at 11:20