method called multiple times [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
My purpose is to define ajax method callback with jquery.
all DOM of parent div are loaded dynamically
i have define delete button foreach comments
and i want to get confirmation from twitter bootrap modal befor throw the ajax request : https://jsfiddle.net/r4sLt016/5/
this.deleteComment = function () {
self = this;
$("button[name='deleteComment']").each(function (index, el) {
$(this).unbind().bind('click', function (event) {
event.preventDefault();
var ref = $(this).attr('data-ref');
var callback = function () {
/*$.ajax({
url: '/path/to/file',
type: 'DELETE',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});*/
alert("multiple");
}
self.confirm("Delete Comment ", "Are you sure you want \
to delete this Comment ?", callback);
});
});
}
this.confirm = function(head, question, callback) {
$(".modal-title").html(head);
var body = $("<p/>").text(question);
$(".modal-body").html(body);
$("#deleteModal").click(function(event) {
callback();
$('.customModal').modal('hide');
});
$('.customModal').modal('show');
}

You are binding the click event deleteModal element everytime you call the confirm() method!
So you have to unbind() and bind() again like you did at the deleteComment buttons.
Like this:
this.confirm = function(head, question, callback) {
$(".modal-title").html(head);
var body = $("<p/>").text(question);
$(".modal-body").html(body);
$("#deleteModal").unbind().bind('click', function(event) {
callback();
$('.customModal').modal('hide');
});
$('.customModal').modal('show');
}
>> Updated JSfiddle!

Related

External Jquery Plugins not working after ajax call content [duplicate]

This question already has answers here:
Making jquery plugins work after an Ajax call
(3 answers)
Chosen not working on elements from AJAX call
(2 answers)
Closed 1 year ago.
So I have this Jquery functions that I've created using delegations and call each functions in the documeny.ready.
$(document).ready(function () {
getContent();
getQuoteButtton();
popupModal();
plugins();
});
function getQuoteButtton() {
// button quote
$("body").on("click", ".btn-quote", function (e) {
var $this = $(this);
$this.toggleClass('quote-selected');
if ($this.hasClass('quote-selected')) {
$this.text('Selected');
} else {
$this.text('Select This Quote');
}
});
}
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php');
});
}
function popupModal() {
/*Toggle popup-modal class */
$("body").on("click", ".popup-modal-toggle", function (e) {
$('.popup-modal').fadeIn().show();
});
//close popup button
$("body").on("click", ".popup-close", function (e) {
$('.popup-modal').fadeOut().hide(300);
});
}
function plugins() {
// phone number plugin initialized singapore and malaysia only
$("#phone-num").intlTelInput({
initialCountry: "SG",
onlyCountries: ['SG', 'MY'],
utilsScript: './resources/vendors/intl-tel-input-master/js/utils.js'
});
// Select tags with search bar
$(".chzn-select").chosen();
}
The other functions is working fine but when I call the plugins function it doesn't seem to load after using the getContent.
The getContent function is where I handle my ajax call to load each pages in the section using the div element #get_content
I don't understand why my plugins function is not working. Does anybody know why? Do I have to call each functions in plugins to use delegations also? if so, what's the process? Thanks.
EDIT - Correct Answer
I have find out the solution, in the getContent function, I also added the plugins() function inside to fetch it after ajax. I don't know why this question was closed even though I have a different approach in coding.
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php', function (response, status, xhr) {
// include the plugins function after the content loads -> if no initialization function won't load
plugins();
});;
});
}

After replacing HTML js function is not bound anymore [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I suppose my function isn't correctly defined since when I replace table html code, table rows don't trigger anymore the function they are bound with.
Here is my HTML table:
<tr class="open-row-modal" href="/dashboard_staff/settings/ajax_update_period/1" data-toggle="modal" data-target="#form-modal">
<td>bla bla</td>
<td>30,00</td>
</tr>
And my javascript code:
var formAjaxSubmit = function(form, modal, obj_to_replace = false) {
$(form).submit(function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (xhr, ajaxOptions, thrownError) {
if ( $(xhr).find('.has-error').length > 0 ) {
$(modal).find('.modal-body').html(xhr);
formAjaxSubmit(form, modal);
} else {
$(modal).modal('toggle');
if (obj_to_replace !== false) {
$(modal).modal('toggle');
obj_to_replace.parentNode.innerHTML = xhr;
}
}},
error: function (xhr, ajaxOptions, thrownError) {
// handle response errors here
}
});
});
};
$('.open-row-modal').click(function() {
var url = $(this)[0].attributes.href;
var parent_card = findAncestor($(this)[0], 'card-default');
let load = $('#form-modal-body').load(url.value, function () {
$('#form-modal').modal('toggle');
formAjaxSubmit('#form-modal-body form', '#form-modal', parent_card);
});
});
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
When the table is replaced, the click function is not triggered anymore.
I think it's because the elements are dynamically updated. Try using event delegation to handle the event. In jquery, try using .on() to attach the click event to the document selectors
$(document).on('click','.open-row-modal',function() {
See https://api.jquery.com/on/ for documentation about the .on() event handler.

fadeout after jquery get function [duplicate]

This question already has answers here:
JavaScript - Owner of "this"
(6 answers)
Closed 6 years ago.
I've got span inside an LI with a class of removeFile, when clicked, it should remove a file using jQuery $.get and then upon successful deletion, it should fadeout the containing LI. I can't figure out why this is not working, I can get it to alert(data) but not assign to a variable or execute the fadeOut() command.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$(this).parent().fadeOut();
}
});
}
});
<li class="file">
<span class="file" data-file-url="http://demo.com/filemanager/files/test.txt" title="test.txt">test.txt</span>
<span class="removeFile" data-file-url="/files/test.txt"></span>
</li>
Inside ajax callback function this refers to jqXHR object, so you need to define it outside the ajax call as variable or set it the context option.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var $this = $(this);
var fileUrl = $this.data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$this.parent().fadeOut();
}
});
}
});
this in get() not referencing .removeFile. this refers to xhr object in the callback of get().
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var li = $(this).parent(); //added this line
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')) {
$.get('process.php', { 'remove-file': fileUrl }, function (data) {
if (data == 'true') {
li.fadeOut(); //changed this line
}
});
}
});

How to call a function in javascript?

I want to call a function every time my update was successful. The update is working my only concern is the alert pop-up every successful update.
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText)
{
popup();
}
}
});
var popup = function () {
$(document).ready (function(){
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
});
});
};
var popup = function () {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
On the first update, pop-up showed but it doesn't show on the 2nd update
I think it'll solve your issue
$.post(
{
url: 'update_question.php',
data:
{
id: id,
new_question: newText,
},
success: function()
{
that.replaceWith("<section>"+newText+"</section>");
if(text != newText){
popup();
}
}
});
function popup() {
$("#success-alert").alert();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
};
The $(document).ready jquery function waits until the DOM is loaded into your browser before it executes the javascript code contained within it's function scope {}.
So remove $(document).ready from your code.
Also note that single page applications only need to list $(document).ready once and all the listener events you setup are defined within it's body.
So you should have it listed somewhere at least once and then you define all your initial event listeners within its body.

Javascript MVC Controller and Click Events

I'm having a problem with the click events not working using a Javascript MVC Controller.
TEST.Assignments.AssignmentsController = function (element) {
var elements = {
activeAssignmentsPanel: $('#lpn-activeAssignments_Cont'),
assignmentViewLink: $("#lpn-activeAssignments_Cont table tr th a")
};
var _this = this;
var model = new TEST.Assignments.AssignmentModel();
this.buildAssignmentsList = function () {
var assignments = model.getActiveAssignmentsList({
assignmentMode: "active",
mock: true,
success: function (data) {
dust.render("ActiveAssignmentsPanel", data, function(err, out) {
elements.activeAssignmentsPanel.append(out);
});
}
});
};
this.getAssignmentDetails = function(assignmentId) {
console.log(assignmentId);
};
//bind all events
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
};//end assignments controller
$(function () {
var assignmentsController = new TEST.Assignments.AssignmentsController();
assignmentsController.buildAssignmentsList();
});
If you look at the //bind events, I have a click function there that should be working. But it is not. The constructor is being called and the elements are traced out correctly. Any idea why the click event won't work?
I assume the assignmentViewLink elements are created and appended in the success callback. If so, it looks like a sequence problem. When you bind the click event, the assignmentViewLink elements have not been created yet, and hence, the click eventhandler isn't attached.
//bind all events
// assignmentViewLink is empty []
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
To verify this, move the elements.assignmentViewLink(...) into the success callback.

Categories

Resources