Jquery confirm displays text several times - javascript

I have a jquery confirm dialog that takes some values and asks if we want to delete the records for them. The dialog box is prompted when I click a button. The problem is that if I simply close the dialog (not choosing nor Yes neither NO), the next time I open that dialog, it will display the message twice. If I do like this for a third time it displays it 3 times and so on ... Otherwise it works fine. But I want to fix this issue too.
Note: Several messages are displayed inside the same dialog box.
This is my code:
<script>
$(document).ready(function(){
$(".delete-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$("#dialog").dialog({
autoOpen: false,
buttons : {
"Yes" : function() {
$.ajax({ type: "POST", url: "delete_lecturer.php", data: { x: names, y: surname} }) //sends post query to delete the selected row
.done(function( msg ) {location.reload();}) //reloads page in order for the change to take become evident
},"No" : function() {$(this).dialog("close");}
}
});
$("#dialog").dialog("open");
$('<p>Are you sure you want to delete lecturer '+names+' '+surname+'?</p>').appendTo('#dialog');
});
});
</script>
And here I create the div for it:
<div id="dialog" title="Action can not be reversed!"></div>
Im not putting the message inside the div because i need to pass the values name and surname in the message. But I think this is causing the problem.

You need to clear the contents of $("#dialog") for each click, otherwise each click results in an additional paragraph being added to the div.
Change
$("#dialog").dialog("open");
to
$("#dialog").html('').dialog("open");
or even
$("#dialog").html('<p>Are you sure you want to delete lecturer '+names+' '+surname+'?</p>').dialog("open");

$("#dialog").empty().dialog("open");

Related

How to stop multiple jQuery Ajax calls made after multiple times opening different modal windows

Lets imagine that I have a page where all my projects are listed in the table:
ID | PROJECT-NAME | PROJECT-LINK
1 Project 1 | (BUTTON)
2 Project 2 | (BUTTON)
3 Project 3 | (BUTTON)
Now at the moment of clicking (BUTTON) for Project 1 I'm running this JavaScript code:
// on button click opening modal window
$(".modal-button").on('click', function () {
let button = $(this);
const id = button.attr('data-id');
// calling backend to get details necessary for modal popup
$.ajax({
url: "/project?id=" + id,
type: "get",
success: function(response){
if(!response.result){
if(response.error === 'expired'){
$('.expired').show();
} else {
alert(response.error);
}
}
let url = response.url;
let modal = document.getElementById("project-modal");
let span = document.getElementsByClassName("close")[0];
// showing modal popup
$('.copied-text').hide();
$('.expiration-changed').hide();
$('#project-modal').show();
// inserting link to disabled input field
$("#link").val(url);
$("#logo-link").val(response.project_url);
$("#expiration-date").val(response.expiration_date);
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
$('#project-modal').hide()
};
// adding close button
$("#share-close-btn").on('click', function(){
$('#project-modal').hide()
});
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$('#project-modal').hide()
}
};
}
});
$("#date").datepicker({
dateFormat: "yy-mm-dd"
});
// modal button to send new data
$("#copy-btn").on('click', function(){
$('#link').select();
document.execCommand("copy");
this.focus();
let img_url = $("#logo-link").val();
let request_data = {"id": id, "img_url": img_url};
$.ajax({
url: "/projects",
type: "post",
contentType:"application/json",
data: JSON.stringify(request_data),
success: function(response){
if(!response.result){
alert(response.error);
}
}
});
$('.expiration-changed').hide();
$('.copied-text').show();
});
});
Now the JS code, it basically shows $('#project-modal').show(); my hidden modal window (as it is initially with style="disabled: disabled;"), first thing I call back-end to get project data by the id which I get from clicked button (in this case ID=1), by which I know what project I'm updating.
When I need to update back end with new data and I do this first time in the newly loaded page, on click $("#copy-btn").on('click', function(){ to send new data to the back-end, it works fine, sends only 1 POST request to the back-end and updates it correctly.
But, after closing (hiding) Project 1 modal window $('#project-modal').hide(); and opening another Project 2 modal window and sending an update $("#copy-btn").on('click', function(){ to the back-end with ID=2 for some kind of a reason with this I send it 2 requests. 1st request with ID=2 and 2nd request with ID=2.
How can I handle multiple modal window openings without sending multiple requests with previously opened modal window generated ID?
Should I create modal window on the fly and not hide it, but destroy/remove it?
Or the JavaScript code of mine is incorrect and how to improve it?
Or I'm doing at all in a wrong way?
If you need more information on this, please ask, I will update the question. Thank you!
This happens because on each button click opening a modal window like:
$(".modal-button").on('click', function () {
You are adding a new event listener for $("#copy-btn") each time like:
$("#copy-btn").on('click', function(){
So, to resolve this issue you simply need to remove all previous event handlers that were attached with .on() using the .off() method like:
$("#copy-btn").off('click').on('click', function(){

A strange issue with jquery/ajax not updating variables inside a function during onClick

I have a small issue which I can't seem to fix for 3 days. I don't think it
is a code error but my understanding variables and why onClick event doesn't (work) properly
Basically I have a page a table and many rows in it. Each row has comment icon, and when you clicked on this icon, a jquery modal opens up with a textarea and your write your
comment press submit (on the modal) and the comment is sent via ajax.
Everything works except:
The problem is that if I have 10 rows, and without refreshing/reloading the page if I open each of those 10 icons in
one by one, submit my comment, all comments get inserted in the first row.
It is as if, If I open the first popup and submit and when I open a second popup then something about the first popup
is being persisted.
Here is an example code.
this is a simple code to represent the modal
<!-- very minimilized example because the modal has no issues -->
<div class="modal fade" id="comment-viewer">
<input type="comment" name="" id="my-comment">
<input type="button" name="submit" class="btn-primary">
</div>
the table with rows and comment icon that triggers the modal to show (onclick)
<table>
<td><i class="title_row_id_1" onClick="open_comment_modal(this)" data-id="1"></i> </td>
<td><i class="title_row_id_2" onClick="open_comment_modal(this)" data-id="2"></i> </td>
<td><i class="title_row_id_3" onClick="open_comment_modal(this)" data-id="3"></i> </td>
<td><i class="title_row_id_4" onClick="open_comment_modal(this)" data-id="4"></i> </td>
<td><i class="title_row_id_5" onClick="open_comment_modal(this)" data-id="5"></i> </td>
</table>
a function to open modal, and send submitted content to php file
function open_comment_modal(e){
var id = e.dataset.id
// code to display the modal goes here. (has no issues)
$('.btn-primary').click(function(){
var comment = $("#my-comment").val()
var dataString = "id=" + id + "&comment=" + comment
ajaxRequest = jQuery.ajax({
type: "POST",
url: "foo.php",
data: dataString,
success: function(response) {
$("#my-comment").val('') // no effect
}
});
$("#my-comment").val('') // no effect
})
$("#my-comment").val('') // no effect
}
So, in the above example it on each comment icon press it should update the id, get the comment
and send it to db.
But all it does is insert into the database all comments with the 'id' of the first opened comment.
I have disabled caching but nothing still
It's simply because of the id variable scope issue. You are attaching the click handler inside the open_comment_modal method. which you should not. Instead of this you should attach the click handler out side of that function and get the id from the dom dataset inside the click handler.
Second try ;). Please try to change open_comment_modal(e) like:
function open_comment_modal(e){
var id = e.dataset.id
// code to display the modal goes here. (has no issues)
$('.btn-primary').off('click');
$('.btn-primary').click(function(){
...
Because everytime you call open_comment_modal, you append another click handler to the .btn-primary and the old ones are still there. So you have to clear the previous (not valid) handler, before you attach new one.
You need to reset the fields when the popup is closed and repopulate the fields with new values when the modal is shown again.
For example suppose when you close the popup your comment box must be emptied like this
$("#comment-viewer").on("hidden.bs.modal", function () {
$('#my-comment').val('');
});
hope you understand the point..
You need to reset the text once modal is open and read the text once submit button is clicked.
Here is the updated code
var _Id;
var _comment;
function open_comment_modal(e){
_Id = e.dataset.id;
$("#my-comment").val('');
// code to display the modal goes here. (has no issues)
}
$( document ).ready(function() {
$('.btn-primary').click(function(){
_comment = $("#my-comment").val();
var dataString = "id=" + _Id + "&comment=" + _comment
ajaxRequest = jQuery.ajax({
type: "POST",
url: "foo.php",
data: dataString,
success: function(response) {
$("#my-comment").val('');
// code to hide the modal goes here.
}
});
});
});

JQuery UI Dialog dont update on second click

I have this problem with my JQuery UI Modal window. Its used when i click a button, then it opens up and append contents to it trough an Ajax call to a php file. Works perfectly the first time i open it, but then when i click another button that should show different content, it still shows the old content in it, and i have to refresh the page for it to work.
This is my Dialog open event which is triggered by a switch, and the last part which appends data to my select box on creation.
$( "#attack" ).dialog({
resizable: false,
width:"400px",
buttons: {
Attack: function() {
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
$("#users").selectmenu({
create: function( event, ui ) {
$.ajax({
type: "POST",
url: "mapfunctions/FetchUsers.php",
data: {RegionID: RegionID},
success: function(data) {
$("#users").append(data);
}
});
}
});
The dialog looks like this: http://i.imgur.com/02a2GYB.png
The HTML for it is a bit long, so i hope you dont need that dialog code, if so, let me know and i will add.
Its the Select menu which keeps the old data from the first ajax call.
I tried using Destroy and such on close, but then the dialog would simply never open again heh.
Thanks a lot people, hope this is enough for a clear understanding
This is very common problem with ajax and modal windows.. on clicking next button you have to reset the form and load it new.
for eg:
If you are using form with id "myForm" then on clicking another button reset the form like $("#myForm").trigger('reset'); in jQuery. or any other way

Creating a confirmation box jquery php

I have a website where i have comments . now people can delete comments using .del button
$('.del').click(function(){
var id = $(this).attr('cmnt-id');
$.post(url,{
//data sent
},function(data){
//remove the comment div
})
});
Now what i want is a confirmation box to be appear on screen which has simply 2 options delete and cancel. When someone presses delete it deletes but when pressed cancel it returns false.
But i dont know how do i do it.
UPDATE
I have my own confirmation box and dont wanna use any PLUGINS
But how do i take em into action ??
updated fiddle
Try this:
if (confirm('Are you sure you want to delete this?')) {
//delete code, OK was pressed (confirmed), execute delete code
} else {
//cancel was pressed return false
return false;
}
No jquery needed nor fancy box.
If you need something fancy I would suggest using JQuery UI where you can use Dialog widget to have a confirm box.
UPDATE
var confirmed = false;
$('.del').click(function(){
//show your confirm dialog
});
$('.confirm .yes').on('click', function() {
//execute delete code
});
$('.confirm .no').on('click', function() {
//code to close your confirm dialog
});

How do I stop the page reload after selecting an autocomplete suggestion

I made an autocomplete for a form input field that allows a user to add tags to a list of them. If the user selects any of the suggestions, I want the page to use add the new tag to a section of tags that already exist without the page reloading.
I want this to happen with 3 scenarios:
The user types in the tag, ignores the autocomplete suggestions and presses enter.
After typing in any part of a query, the user selects one of the autocomplete suggestions with the arrow keys and presses enter.
After typing in any part of a query, the user clicks on one of the autocomplete suggestions with the mouse.
I have been able to make scenario 1 work flawlessly. However, scenarios 1 and 2 make the page reload and still doesn't even add the tag to the list.
Scenarios 1 and 2 are both called by the same function:
$j("#addTag").autocomplete({
serviceUrl:'/ac',
onSelect: function(val, data){
addTag(data);
}
});
And here is the code for addTag():
function addTag(tag){
var url = '/addTag/' + tag;
//Call the server to add the tag/
$j.ajax({
async: true,
type: 'GET',
url: url,
success:function(data){
//Add the tag to the displayed list of already added tags
reloadTagBox(data);
},
dataType: "json"
});
//Hide the messages that have been displayed to the user
hideMessageBox();
}
Scenario 1 code:
function addTagByLookup(e, tag){
if(e && e.keyCode == 13)
{
/*This stops the page from reloading (when the page thinks
the form is submitted I assume).
*/
e.preventDefault();
//If a message is currently being displayed to the user, hide it
if ($j("#messageBox").is(":visible") && $j("#okayButton").is(":visible")){
hideMessageBox();
}
else{
//Give a message to the user that their tag is being loaded
showMessageBox("Adding the tag <strong>"+tag+"</strong> to your station...",'load');
//Check if the tag is valid
setTimeout(function(){
var url = '/checkTag/' + tag;
var isTagValid = checkTag(tag);
//If the tag is not vaid, tell the user.
if (isTagValid == false){
var message = "<strong>"+tag+"</strong>"+
" was not recognized as a valid tag or artist. Try something else.";
//Prompt the user for a different tag
showMessageBox(message, 'okay');
}
//If the tag is valid
else{
addTag(tag);
}
}, 1000);
}
}
}
I know I used the e.preventDefault functionality for a normal form submit in scenario 1, but I can't seem to make it work with the other scenarios and I'm not even sure that is the real problem.
I am using pylons as the MVC and using this tutorial for the autocomplete.
So in case anyone wants to know, my problem was had an easy solution that I should have never had in the first place.
My input tag was embedded in a form which submitted every time the input tag was activated.
I had stopped this problem in scenario 1 by preventing the default event from occurring when the user pressed enter. But since I didn't have access to this event in the jQuery event .autocomplete(), I couldn't prevent it.

Categories