I have this script :
$(window).load(function () {
$(document).on('click', '.btn-delete-confirm', function () {...});
});
and I have this element :
<div id="attachments"></div>
and I have this script to load some html :
$(document).on('click', '.nav-tabs li a[href="#attach"]', function () {
$.ajax({
url: loadAttachmentsURL,
data: { equipmentId: equipmentId },
success: function (data) {
$("#attachments").html(data);
}
});
});
in my result from ajax I have some button that have .btn-delete-confirm class but when clicked on them nothing happen .
the sample of result like this :
<td><a data-id="73b2db39-199c-845c-8807-6c6164d2d97d" data-url="/Admin/EquipmentAttachment/Delete" class="btn-delete-confirm btn">Delete</a></td>
how can I resolve this ?
one way will be by attaching click event after html is set:
$(document).on('click', '.nav-tabs li a[href="#attach"]', function() {
var equipmentId = "?";
var loadAttachmentsURL = "/url";
$.ajax({
url: loadAttachmentsURL,
data: {
equipmentId: equipmentId
},
success: function(data) {
$("#attachments").html(data);
$(".btn-delete-confirm").click(function() {
alert("click!");
});
}
});
});
another will be attaching the click event to the document context:
$(document).on('click', ".btn-delete-confirm", function() {
alert("click!");
});
$(document).on('click', '.nav-tabs li a[href="#attach"]', function() {
var equipmentId = "?";
var loadAttachmentsURL = "/url";
$.ajax({
url: loadAttachmentsURL,
data: {
equipmentId: equipmentId
},
success: function(data) {
$("#attachments").html(data);
}
});
});
You are trying to add an eventlistener to something that isnt there yet.
This will result in an error, and the event wont fire again.
So try to add the listener AFTER the ajax import.
$(document).on('click', '.nav-tabs li a[href="#attach"]', function () {
$.ajax({
url: loadAttachmentsURL,
data: { equipmentId: equipmentId },
success: function (data) {
$('#attachments').html(data);
$('.btn-delete-confirm').on('click', function () {...});
}
});
});
Though .delegate() method is deprecated in jquery-3.0, its description is still worth to have a look:
Attach a handler to one or more events for all elements that match the
selector, now or in the future, based on a specific set of root
elements.
Exmaple:
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
Using document as a root element is not a big problem, but have you tried #attachments ?
$(window).load(function () {
$("#attachments").on('click', '.btn-delete-confirm', function () {...});
});
Related
When i click on a <span>, the span changes to an input field
$('table td').on('click', 'span', function() {
var $el = $(this);
var $input = $('<input/>').val($el.text()).attr('class', 'form-control');
$el.replaceWith($input);
var save = function() {
var $p = $ ('<span>').text( $input.val() );
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$('input').on('change', function() {
var target = $(this);
$.ajax({
url: 'url',
data: {
value: target.val(),
ruleId: target.data('rule'),
date: target.data('date')
},
type: 'POST',
success: function(data) {
console.log('updated');
}
});
});
After it, i need to catch when the input changes
But it does not trigger the $('input').on('change', function() { function anymore...
Can you try to use this instead
$(document).on('change','input',function(){
// your code here
}
Hope the helps
bind event to document and not to element will solve your problem.
$(document).on('change', '.item', function(event) {
refer jQuery doc
I had an issue with delete button.
ex: I press delete at driver 1 and choose no, after that I press delete at driver 2 and choose yes. driver 1 also deleted automatically.
here's my delete button code :
$(document).ready(function(){
$('#datatable tbody').on('click', '.delete', function(event) {
event.preventDefault();
$('.modal-header h4').html($(this).data('title'));
$('.modal-body p').html($(this).data('message'));
var url = $(this).data('url');
var datatable = $('#datatable').DataTable();
$('#confirmDel').on('click', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('.modal-body input[name="_token"]').val()
},
url: url,
type: "DELETE",
success: function (data) {
console.log(data);
datatable.ajax.reload();
$.gritter.add(
{
title: "Record has been deleted succesfully",
});
},
error: function (data) {
console.log(data);
}
});
$('#modalDelete').modal('hide');
});
});
});
Any Idea ?
Do you use the same button with id ConfirmDel inside the modal?
Try unbinding the button event:
$('#confirmDel').unbind('click');
Before binding it again:
$('#confirmDel').on('click', function(e) { ...
I think this is an event bubble. Clicking on child element will fire the
click event on parent element also.
try something like this:
child.on('click', function(e){
e.stopPropagation();
});
I have this JQuery expression where i push a button, get some HTML from the server and then append it to a DOM node in my document:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").click(function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
});
});
});
</script>
I have multiple ".addButton" buttons on my web site. The problem im experiencing is that after multiple clicks on the buttons my .done handler is being called multiple times.
My guess is that i have a list of event handlers that are being executed, I cant understand where / why this is done or how I prevent it from happening.
The problem is not taht you do the request is done more then once rathern then it calls done after its done.. you can keep the state in data object::
$(document).ready(function () {
var posting = false;
$(".addbutton").data("done", false).click(function () {
var addbuttonNode = $(this);
if (!addbuttonNode.data("done")) {
addbuttonNode.data("done", true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data);
});
}
});
});
I would do the following:
$(".addbutton").click(function () {
var addbuttonNode = $(this);
addbuttonNode.attr('disabled',true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
addbuttonNode.attr('disabled',false);
});
});
You could check it for any request pending:
$(document).ready(function () {
$(".addbutton").click(function () {
// if any request pending, return {undefined}
if ($.active) return;
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
If you wish instead each button to be clickable only once, then use jQuery .one() method:
$(document).ready(function () {
$(".addbutton").one('click', function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
Try to use bind, and unbind functions for the event handling. Then You can unbind the click function after it was executed once.
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").bind('click',function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
addbuttonNode.unbind('click');
});
});
</script>
Another way of doing nearly the same, I think this should be better:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").each(function(){
$(this).bind('click',function () {
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
$(this).unbind('click');
});
});
});
</script>
I haven't tried it yet, but it should work, try it! :)
You can also set up a class or data attribute to check if the button was already clicked. You can then exit from the script like if($(this).hasClass('clicked')) { return; } or something...
I am developing a jquery module for add delete edit view etc.
My problem is when page load complete, a list of items populate. After selecting an item this item's subitems loaded via jquery and html built, appended. But on this table event not fired up. Jquery Live is no longer available. Instead "On" is not working.
I tried :
$(document).on('click', selector , function () { foo(); });
But when a button is clicked it triggers other buttons as well.
My code is below.
I have a working code except links on table which loaded by jquery.
var myModule = {
el: {
listbutton: $('#list-button'),
listcontainer: $('#list'),
detailbutton: $(".item-detail"),
deletebutton: $(".item-delete"),
editbutton: $(".item-edit")
},
init: function() {
...
myModule.el.listbutton.on("click",myModule.getMainData);
},
getMainData: function() {
...
success: function(data) {
myModule.BuildTable(data.Value.DataList);
}
...
},
BuildTable: function (hws) {
var c = "";
c += "<table>";
$.each(hws, function() {
c +=
'<tr>' +
'<td>' + this.Title + '</td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<tr>';
});
c += "</table>";
myModule.el.listcontainer.empty().append(c);
myModule.TableLinks();
},
itemDetails: function () {
alert("Detail clicked");
},
itemDelete: function () {
alert("Delete clicked");
},
itemEdit: function () {
alert("Edit clicked");
},
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
$(document).on('click', myModule.el.deletebutton, function () { myModule.itemDelete(); });
$(document).on('click', myModule.el.editbutton, function () { myModule.itemEdit(); });
},
};
myModule.init();
Can you try following:
TableLinks: function () {
$(document).on('click',
".item-detail",
function (ev) {
myModule.itemDetails();
ev.stopPropagation();
}
);
$(document).on('click',
".item-delete",
function (ev) {
myModule.itemDelete();
ev.stopPropagation();
});
$(document).on('click',
".item-edit",
function (ev) {
myModule.itemEdit();
ev.stopPropagation();
});
},
you need the delegation
$("selector on which item is added").on("click", "new item selector", function(){
});
ON and Delegate
You have to do something like this to use the "on" method.
$("table").on("click", myModule.el.detailbutton, myModule.itemDetails());
UPDATE: Just noticed, you have to used a selector not a jQuery object in the second parameter.
So $("table").on("click", ".item-detail", myModule.itemDetails());
your approach using on is exactly what you need, but should have been bit more careful on constructing the element object
el: {
listbutton: '#list-button',
listcontainer: '#list',
detailbutton: ".item-detail",
deletebutton: ".item-delete",
editbutton: ".item-edit"
},
and use it like this
init: function () {
$(myModule.el.listbutton).on("click", myModule.getMainData);
},
what you did is
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
...
},
which is similar to and which is wrong
TableLinks: function () {
$(document).on('click', $(".item-detail"), function () { myModule.itemDetails(); });
....
},
working fiddle
i have tried to execute some code inside the ajax complete event but it doesn't work on the page load event , but it works perfectly in the onchange link event
$(document).ready(function() {
$.ajax({
beforeSend: function() {
// Handle the beforeSend event
},
complete: function() {
// Handle the complete event
$("#customfields_1 :input").filter(function() {
return $.trim(this.value).length === 0;
}).closest("td").hide();
}
// ......
});
});
$(document).ready(function() {
$.ajax({
url: 'http://foo.bar.com/some.json', // this is the important part
beforeSend: function() {
// Handle the beforeSend event
},
complete: function() {
// Handle the complete event
$("#customfields_1 :input").filter(function() {
return $.trim(this.value).length === 0;
}).closest("td").hide();
}
// ......
});
});