Link click event by class in javascript doesnt work - javascript

I have a table with some <td>s and I have a link to delete each row with the class of '.DeleteMe'.
I have an AJAX post call in jQuery, but when I click on a link, it does nothing (click event doesn't work).
$(document).ready(function() {
$(".DeleteMe").click(function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});
And here is the link on the each row:
<a class="btns delete-icon DeleteMe" data-deleteid="#item.id">Delete</a>
How can I get these links to work?

I guess, that your rows are created dynamically after your event has been attached. In this case I would recommend to use event-delegation instead:
$(document).ready(function() {
$(document).on('click', '.DeleteMe', function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});

Related

jQuery Load And Ajax Forms Not Working Together

I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});

nesting ajax post in json get

function test() {
$.getJSON("/Home/GetAp", function (result) {
$.each(result, function () {
if (this.is_disabled == "False") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else if (this.is_disabled == "True") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton2" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else {
return null;
}
})
})
}
How would I nest and ajax function be able to POST the a.val() so that when a user clicks on any $("#infobutton") they will be able to use the val of that button which would be an id specific to that button
$("#infobutton").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Home/setID",
data: JSON.stringify({ id: this.id }),
success: function (result) {
}
});
});
Do not make your logic depend on duplicate ids of DOM elements, use class instead.
Use event delegation to register event handlers for elements that exist at the time of event registration and for elements that will be created later.
.append('<div id="imagewrap"><img class="infobutton" src="/Content/information%20icon.png" /></div>')
$(document).on("click",".infobutton",function () {
$.ajax({
...
});
});
No need to nest ajax call. Just ensure click events bind to new elements appended and get the id in click event handler. Similar example (without ajax call)
$(document).ready(function(){
$(document).on('click', '.info', function(e) { alert("clicked div # " + $(e.target).text()); });
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 1.</div>"); }, 1000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 2.</div>"); }, 2000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 3.</div>"); }, 3000);
});
<div id="d1">
</div>
Let me know if you need more details or example with ajax call.
For id you can use
$(document).on('click', '.info', function(e) { alert("clicked div # " + e.target.id); });

How can I prevent a click event from firing when I call "<element>.click()"? Or what's a better way to solve this issue?

$(function() {
$(".universeLink").click(function (e) {
e.preventDefault();
var link = this;
alert(link.id);
$.ajax({
type: 'GET',
url: "#Url.Action("IsUniverseCached", "Universes")" + "?universeId=" + (link.id),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
if (returnedData === false) {
alert(returnedData);
$("#" + link.id).empty();
$("#" + link.id).html("<div class=\"alert alert-warning\"><strong>Not cached</strong> — this data will take a while to arrive!</div>");
}
$("#" + link.id).click();
},
error: function () {
alert("Error");
}
});
});
});
I am building some JQuery to make a request before the original request is followed.
At the end of the success block, $("#" + link.id).click(); is called and the event is fired again. I tried something similar with (element).submit() on a form, and the .submit() event did not fire again, so I assumed I could do the same trick with .click().
Here's the HTML elements.
<a id="10" href="/Universes/ViewUniverse?universeId=10&regionId=8" class="universeLink">1</a>
(the ID is dynamically assigned)
Just redirect the browser to the new location. I.e. instead of using .click, assign to window.location.href:
window.location.href = link.href;

Calling a click event of a dynamically created element

I'm pretty new to all things javascript related, and I seem to have got myself in a pickle. I'm creating a site which displays a seating plan of an office. When the page loads, I load data retrieved from the database, into a function that loops through it and creates an anchor for each person.
This is my method:
function getDesks(coordsArr) {
for (var i = 0; i < coordsArr.length; i++) {
var element = $("<a href='' class='deskBtn' data-name='" + coordsArr[i].UserName + "'>.</a>");
$(element).css({
"top": coordsArr[i].DeskYCoord,
"left": coordsArr[i].DeskXCoord
}).appendTo(".map");
}
}
The problem i'm having is where to place the following ajax click event.
$('.deskBtn').on('click', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
I tried placing it after the for loop, but when I click one of the anchor tags the data gets logged to the screen, however, it quickly vanishes. Any suggestions would be great.
Why can't you just add the handler inside the for loop?
$(element).on('click', function() { ... })
Delegate the event to a static element. Do it for body:
$('body').on('click', '.deskBtn', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
You should try with a live
$(document).ready(function(){
$('.deskBtn').live('click', function(){
});
});

JQuery prevent links working whilst ajax is loading

I have a firework detonation system which uses JQuery to connect to a PHP script via AJAX to detonate the fireworks. The only problem is that if you click one launch button straight after another, there is a possibility of setting off more fireworks than you want.
I need a way to disable all other links on the page until the ajax has finished and received a response. I have tried:
//Prevent clicks
$("body").find("a").click(function (e) { e.preventDefault(); });
//Re-enable clickable links
$("body").find("a").unbind("click");
My current ajax script is:
$(document).ready(function() {
$(".button").on("click",function() {
//Disable all other links
$.ajax({
type: "POST",
url: "launch.php",
data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
success: function(e) {
//Re-enable other links once ajax is complete
}
});
return false;
});
});
What would be even better is, if the buttons were to grey out whilst waiting for the response. I have a demo script at http://joshblease.co.uk/firework/
One way using a variable disabled
$(document).ready(function() {
var disabled = false;
$('a').css('opacity','0.4');
$(".button").on("click",function() {
//Disable all other links
disabled = true;
$.ajax({
type: "POST",
url: "launch.php",
data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
success: function(e) {
//Re-enable other links once ajax is complete
disabled = false;
$('a').css('opacity','1');
}
});
return false;
});
});
$('a').click(function(event){
if(disabled)
event.preventDefault();
});
Update
Changed link opacity for a disabled effect.
I would use actual buttons, not links, and disable them when one is clicked. Use a class on the button distinguish it from other buttons that might be on the page.
<input type="button" class="launch" ... >
...
$(document).ready(function() {
$("input[type=button].launch").on("click",function(event) {
// We will handle the button, prevent the standard button press action.
event.preventDefault();
//Disable all other links
$('input[type=button].launch').disable();
$.ajax({
type: "POST",
url: "launch.php",
data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
success: function(e) {
//Re-enable other links once ajax is complete
$('input[type=button].launch').enable();
}
});
return false;
});
});
Further manage it with a flag as #MonkeyZeus suggests.
I'd manage this with a class (assuming there might be some links you want to work). All the links that you want to not work give them the class blockable.
You can also then style your a.disabled class in your css to grey out the links (or whatever you want)
$(document).ready(function() {
$(a.blockable).click(function(e) {
if($(this).hasClass('disabled'))
{
e.preventDefault();
}
}
$(".button").on("click",function() {
$('a.blockable').addClass('disabled');
$.ajax({
type: "POST",
url: "launch.php",
data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
success: function(e) {
$('a').removeClass('disabled');
}
});
return false;
});
});
I would approach this by declaring a variable and only allowing AJAX to fire if variable has not been tripped:
$(document).ready(function() {
var launch_processing = false;
$(".button").on("click",function() {
if(launch_processing === false){
launch_processing = true;
$.ajax({
type: "POST",
url: "launch.php",
data: {FID:$(this).attr('id'),Length:$('#FireLength').val()},
success: function(data) {
},
complete: function(){
launch_processing = false;
}
});
}
else{
alert('Are you mad?!?! Fireworks are in progress!');
}
});
});

Categories