Click event listener on elements with the class stops working after first click - javascript

I have an anchor element with a class called .trigger. I have a listener for that class which opens a modal using the iziModal framework. On first click the function works as expected. On second click the listener does not work. Instead i get in console "$(...).iziModal is not a function". What am i doing wrong? Any help would be greatly appreciated. I am bot of a newbie with JS.
** Jquery ver **
3.6.3
Ajax Example 8
$(document).on('click', '.trigger', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var wtitle = $(this).data('title');
$('#my-modal').iziModal({
title: wtitle,
bodyOverflow: true,
width: 600,
headerColor: '#000',
fullscreen: false,
openFullscreen: false,
transitionIn: 'fadeInDown',
transitionOut: 'fadeOutUp',
onOpening: function(modal) {
modal.startLoading();
$.ajax({
url: url,
type: 'GET',
success: function(data) {
modal.stopLoading();
modal.setContent(data);
},
error: function() {
alert('Error loading content.');
}
});
}
});
$('#my-modal').iziModal('open');
});
I have tried initialising the izi modal outside of the trigger event (suggested by ChatGPT).
I think this would work but I am not sure how to pass the URL from the onClick event to $('#my-modal').iziModal(). If someone could suggest that then i could try.
// Initialize the iziModal
$('#my-modal').iziModal({
title: '',
bodyOverflow: true,
width: 600,
headerColor: '#000',
fullscreen: false,
openFullscreen: false,
transitionIn: 'fadeInDown',
transitionOut: 'fadeOutUp',
onOpening: function(modal) {
modal.startLoading();
$.ajax({
url: '',
type: 'GET',
success: function(data) {
modal.stopLoading();
modal.setContent(data);
},
error: function() {
alert('Error loading content.');
}
});
}
});
// Bind the click event to the trigger element
$(document).on('click', '.trigger', function(event) {
event.preventDefault();
event.stopPropagation();
var url = $(this).attr('href');
var wtitle = $(this).data('title');
// Set the modal title
$('#my-modal').iziModal('setTitle', wtitle);
// Set the modal content
$('#my-modal').iziModal('setContent', '');
$('#my-modal').iziModal('startLoading');
$.ajax({
url: url,
type: 'GET',
success: function(data) {
$('#my-modal').iziModal('stopLoading');
$('#my-modal').iziModal('setContent', data);
},
error: function() {
$('#my-modal').iziModal('stopLoading');
alert('Error loading content.');
}
});
// Open the modal
$('#my-modal').iziModal('open');
});

Related

AJAX Unload not firing

I need to run a process when the user exists or leaves a page. I have the following code that I received from another SO question I posted:
<script>
var unloaded = false;
$(window).on('beforeunload', unload);
$(window).on('unload', unload);
function unload() {
if (!unloaded) {
$.ajax({
type: 'post',
async: false,
url: '/Function/Left/#ViewBag.ID',
success: function () {
unloaded = true;
$('body').css('cursor', 'default');
},
timeout: 5000
});
}
}
The problem is that the /Function/Left event is NEVER fired. Is something wrong?

Can't figure out why this ajax request fires two times

I am working on this snippet of code, but I can't figure out why the ajax request is firing up twice when I click the selected button:
$('#passwd-nuova').blur(function() {
var response = $('#passwd-nuova').validate({
'classeform': 'form-utenti',
'empty': 'passwd-nuova'
});
if (!response.empty) {
$('#reset').addClass('btn-disabled');
} else {
$('#reset').removeClass('btn-disabled');
/*
* RESET PASSWORD PANNELLO
*/
$('#reset').on('click', function() {
var new_passwd = $('input[name=passwd-nuova]').val();
var selezionato = $(this).loadID({
'nometabella': 'utenti',
'abbr': 'utenti'
});
var send_email = $('#cb-email').prop('checked');
$.ajax({
cache: false,
type: "POST",
url: "/gutenti/",
dataType: "json",
data: {
'mod-passwd': true,
'idu': selezionato,
'new-passwd': new_passwd,
'send-email': send_email
},
success: function(response) {
var tab = $("#datatable_utenti").dataTable();
$('#modal-reset').modal('hide');
tab.fnDraw();
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'success',
msg: 'modifica completata con successo',
time: 800
});
$('input').each(function() {
$(this).val('');
});
$("#datatable_utenti tbody").compileForm({
'abbr': 'utenti',
'nometabellaDB': 'admin_utenti',
'nometabella': 'utenti'
});
$(document).stato(profile, 'base');
return;
},
error: function() {
console.log("errore async");
$('#modal-reset').modal('hide');
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'error',
msg: 'qualcosa è andato storto, riprova',
time: 800
});
}
});
return;
});
}
});
I've tried to disable the button after the call, and also to return nothing to exit from the function, but nothing has worked.
Your $('#passwd-nuova').blur handler binds the $('#reset').click' handler multiple times.
I'm glad my comment helped you out ;)
I have called the function inside the blur funciton. However; The function is going to be called also when you click the #reset button. I hope it works.
$('#passwd-nuova').blur(function() {
var response = $('#passwd-nuova').validate({
'classeform': 'form-utenti',
'empty': 'passwd-nuova'
});
if (!response.empty) {
$('#reset').addClass('btn-disabled');
} else {
$('#reset').removeClass('btn-disabled');
/*
* RESET PASSWORD PANNELLO
*/
$('#reset').click();
}
});
$('#reset').on('click', function() {
var new_passwd = $('input[name=passwd-nuova]').val();
var selezionato = $(this).loadID({
'nometabella': 'utenti',
'abbr': 'utenti'
});
var send_email = $('#cb-email').prop('checked');
$.ajax({
cache: false,
type: "POST",
url: "/gutenti/",
dataType: "json",
data: {
'mod-passwd': true,
'idu': selezionato,
'new-passwd': new_passwd,
'send-email': send_email
},
success: function(response) {
var tab = $("#datatable_utenti").dataTable();
$('#modal-reset').modal('hide');
tab.fnDraw();
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'success',
msg: 'modifica completata con successo',
time: 800
});
$('input').each(function() {
$(this).val('');
});
$("#datatable_utenti tbody").compileForm({
'abbr': 'utenti',
'nometabellaDB': 'admin_utenti',
'nometabella': 'utenti'
});
$(document).stato(profile, 'base');
return;
},
error: function() {
console.log("errore async");
$('#modal-reset').modal('hide');
$(window).scrollTop(0);
$(document).genAlert({
tipo: 'error',
msg: 'qualcosa è andato storto, riprova',
time: 800
});
}
});
return;
});
I guess that this line:
$('#reset').on('click', function() {
........
runs more than once(on each blur).
You can bind an event more than once with no problem.
Check if this solves your problem:
$('#reset').off('click').on('click',function(){ .....
If it does, then try to move the "event attachment" to a different place.
Jquery - 'on' and 'off'
Try unbind / bind the click callback:
var callback = function () { ... }
$('#reset').unbind('click', callback);
$('#reset').bind('click', callback);
If you attach the click event twice, it will get called two times.

Popup window opens once after close unless refresh

I have a problem that I'm stuck with. I have MVC 3 application and in this application I have the concepts of Survey and Training. Each Training having 1 Survey. To let the users take Survey I open a pop-up page when the HTML actionlink clicked. Below is the code for this in DetailsSurvey.cshtml:
<tr> <td class="view_detail_label">
Eğitim Adı
</td>
<td>
#Html.ActionLink(
training.Name.Name,
"AddSurvey",
new {
employeeId = Model.Id,
trainingId = training.Id
},
new {
#class = "addSurvey"
}
)
<div class="result" style="display:none;"></div>
</td>
</tr>
Then in javascript side I have following functions to open popup:
$(document).ready(function () {
$('.addSurvey').click(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
} //enf of success function
}); //end of ajax call
return false;
});
});
$(document).delegate('.addSurvey', 'click', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: false,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
} //enf of success function
}); //end of ajax call
});
There can be 1 or more Survey links. What happens is when I click the button, pop up windows opens for the first time but when I close the popup window and try to reopen it, it does not open at all. If i open it in new tab or window it opens respectively. I used delegate subscribe the event but it does not work. Is this caused by the action taken by close button, it somehow loses the functionality after closing. Are there are any fixes?
<tr> <td class="view_detail_label">
Eğitim Adı
</td>
<td>
#Html.ActionLink(
training.Name.Name,
"AddSurvey",
new {
employeeId = Model.Id,
trainingId = training.Id
},
new {
#class = "addSurvey"
#onclick="javascript:OpenSurveyPopup();"
}
)
<div class="result" style="display:none;"></div>
</td>
</tr>
<script type="text/javascript">
function OpenSurveyPopup()
{
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
} //enf of success function
}); //end of ajax call
return false;
});
}
</script>
Also remove $(document).ready() and $(document).delegate().
This will work. Thanks.
I solved problem using the following live function, what i did is: In close action of popup I called my controller and re render the page now it works like a charm.
$('a.addSurvey').live('click', function (e) {
var $this = $(this);
e.preventDefault();
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true,
close: function () { console.log("onClose"); $('.surveyTable').load('Home/DetailsSurvey', {id:#Model.Id}); }
}); //end of dialog
console.log($(this).next('.result'));
}, //enf of success function
complete: function () {
console.log("Complete");
},
error: function () {
console.log("Error");
}
}); //end of ajax call
}); //end of live

Ajax form in qTip2

I have a table with a list of names, their attributes and comments for each record. I want to be able to display the comments in a tooltip, and also be able to update those comments via Ajax. I would like to show a tooltip or a modal by clicking on a link. This modal will have a textarea with the comments preloaded. The user can modify the comments and submit them to the action page via Ajax. On successful submission the existing tooltip content will also need to be updated.
Any help would be greatly appreciated.
I am using the qtip2 and tipsy plugins.
I am loading the form in the qTip2 tooltip, onclick, through ajax. The link to the form is brought over from the rel tag. Now when I submit the form, it doesn't submit through ajax but directly the action page. This is my JS code:
$('.commentsedit').each(function()
{
// We make use of the .each() loop to gain access to each element via the "this" keyword...
$(this).qtip(
{
content: {
// Set the text to an image HTML string with the correct src URL to the loading image you want to use
text: '<img class="throbber" src="images/throbber.gif" alt="Loading..." />',
ajax: {
url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
},
title: {
text: $(this).attr('title'), // Give the tooltip a title using each elements text
button: true
}
},
position: {
at: 'bottom center', // Position the tooltip above the link
my: 'top right',
viewport: $(window), // Keep the tooltip on-screen at all times
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true // Only show one tooltip at a time
},
hide: 'unfocus',
style: {
classes: 'my_width_setting_class qtip-wiki qtip-light qtip-shadow'
},
events: {
render: function(event, api) {
// Capture the form submission
$('form', this).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':textarea', this);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: 'commentsform.cfm',
data: $(this).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', data.message + ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
});
}
}
})
})
Although an old question, I think that someone will find useful the solution proposed to a similar problem in the qtip2 developer's site and specifically in
http://craigsworks.com/projects/forums/showthread.php?tid=3680
Edit: in response to a comment I reproduce the main part of the answer as a reference:
$('a[class=qTipForm][rel]').each(function(){
var formName = $(this).attr('name');
$(this).qtip({
content: {
//text: '<iframe src="'+$(this).attr('rel')+'" height="400px" width="700px" frameborder="0"></iframe>',
text: 'Loading...',
ajax: {
url: $(this).attr('rel'),
success: function(data) {
// Set the tooltip contents
this.set('content.text', data);
// Bind the form submit event
$('#' + formName).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':input','#' + formName);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: $('#' + formName).attr('action'),
data: $('#' + formName).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
})
}
},
title: {
text: $(this).attr('title'),
button: true
}
},
position: {
my: 'center',
at: 'center', // Position the tooltip above the link
target:$(window),
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true, // Only show one tooltip at a time
modal: true
},
hide: false,
style: {
classes: 'viewTipForm ui-tooltip-rounded ui-tooltip-light',
tip: false
}
})
.click(function(event) { event.preventDefault(); });
})

error from dialog when using jquery and ajax

I get a an alert: Object XMLHttpRequest. This happens when I click Add Recipient on my dialog. The code below POSts the new values to the database. It opens a dialog or form and the action of the form is to add or insert a new value to the database. I pasted the code below because I think thats likely the source of the error.
Below is the javascript for my code:
$(function () {
$('#dialog-form-add').dialog({
autoOpen: false,
modal: true,
height: 425,
width: 475,
buttons: {
'Add Recipient': function () {
$.ajax({
type: "POST",
url: $("#add-recipient-form").attr('action'),
data: $("#add-recipient-form").serialize(),
dataType: "text/plain",
success: function (response) {
$('#dialog-form-add').dialog('close');
$("#grid").load('/Default/ #grid', function () {
$('tbody > tr:first')
.effect("highlight", {}, 2000);
});
},
error: function (response) {
alert(response);
$('#dialog-form').dialog('close');
}
});
},
Cancel: function () {
$('#dialog-form-add').dialog('close');
}
}
});
$('#requestdate').datepicker({ dateFormat: 'yy-mm-dd' });
$('#add-recipient')
.button().click(function () {
$('#dialog-form-add').dialog('open');
});
});

Categories