I am still quite new to JQuery and I am trying to make a simple pop-up message to confirm a delete, but I want the table row to turn red during this process.
I found this code that seems sweet, short, and simple.
$(document).ready(function(){
$('.confirm').click(function(){
var answer = confirm("Are you sure you want to delete this item?");
if (answer){
return true;
} else {
return false;
}
});
});
from: http://brettgregson.com/programming/how-to-make-a-are-you-sure-pop-up-with-jquery/138
And I am "attempting" to add it onto my current deleteFunction(), but I am still pretty new to JQuery and I am having some "bugs" with it.
My deleteFunction (no confirmation - but color updating works fine)
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
My insertion of the confirmation box works, but does not update the tr background color, nor does it revert the color back to the default upon cancellation.
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$(document).ready(function () {
var answer = confirm("Are you sure you want to delete this item?");
if (answer) {
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").remove();
return true;
} else {
$(element).closest("tr").css('background-color', 'default');
return false;
}
});
}
If someone could explain why the CSS color is not being touched until after the confirmation box appears (or why it does not remove the color after Cancel is pressed) it would be very much appreciated.
I've created a jsfiddle for you: working sample. As for clearing the color, you should use css('background-color', 'initial'). As for highlighting - it should highlight, as sample does. If it does not help, then feel free to reveal your html markup, most likely the issue is there
You can call your delete function if user wants to delete, like this way
here is your delete function:
function deleteFunction(element) {
var newID = $(element).closest("td").find("span.ID").text();
$(element).closest("tr").css('background-color', 'red');
$.post(
'#Url.Action("customDelete", "Movie")',
{
'id': newID
},
function (data) { },
"json"
);
$(element).closest("tr").hide();
}
and here is cofirm to delete:
$(document).ready(function(){
var ans=confirm("Are you sure you want to delete this item?");
if(ans)
{
deleteFunction(element);
}
else
{
return false;
}
});
Related
I wrote an ajax function where on blur the input values are written to the DB, but one input needs to run through two ajax functions:
The first ajax creates a row and checks for duplicates (if a duplicate exist then popup an alert div, if not, see duplicate its only update)
The second ajax updates a row (if a duplicate exists, popup alert div, if not, see duplicate its only update).
Problem is that after the ajax executes the alert popup (div), it shows and immediately closes. When the second time focus and blur happen on that input all is OK. On hide no problems.
I realise that the problem is when setTimeout() or hide() are present and run twice. When they run once, then all is OK.
In my code both setTimeout() and hide() are present.
If I delete the setTimeout() then it's working, but it's closed immediately. I need a delay for a few seconds to show the success message. I tried adding a delay: but no luck.
If I try bind('hide'), unbind('hide'), then only the popup appears and no auto hide is happening.
$(document).ready(function() {
$(".input1, .input2, .input3, .input4, .input5, .input6").blur(function() {
inv_header_footer_ajax(function result_inv(data){
if(data == 1){
$('.alert-icon-3').removeClass('fa-warning').addClass('fa-check').css("background-color", "green");
setTimeout(function () {
$('#alert-popup-3').hide(function() {
$('#alert-popup-3').removeClass('alert-show');
$('#alert-popup-content-3').text('Successful');
});
}, 4000);
document.getElementById("input5").style.borderColor = "";
} else {
$('.alert-icon-3').removeClass('fa-check').addClass('fa-warning').css("background-color", "red");
$('#alert-popup-3').show(function() {
$('#alert-popup-3').addClass('alert-show');
$('#alert-popup-content-3').text('Allert INV !!!');
});
document.getElementById("input5").style.borderColor = "red";
}
});
inv_rows_ajax();
inv_kpo_ajax();
});
});
$(document).ready(function() {
var q = document.getElementById("input1");
var w = document.getElementById("input1");
q.addEventListener("blur", insert_update_kpo_row);
w.addEventListener("blur", kpo_check);
function kpo_check(){
inv_kpo_ajax(function result_kpo(data){
if(data == 1){
$('.alert-icon-4').removeClass('fa-warning').addClass('fa-check').css("background-color", "green");
setTimeout(function () {
$('#alert-popup-4').hide(function() {
$('#alert-popup-4').removeClass('alert-show');
$('#alert-popup-content-4').text('Successful');
});
}, 4000);
document.getElementById("input1").style.borderColor = "";
} else {
$('.alert-icon-4').removeClass('fa-check').addClass('fa-warning').css("background-color", "red");
$('#alert-popup-4').show(function() {
$('#alert-popup-4').addClass('alert-show');
$('#alert-popup-content-4').text('Allert KPO !!!');
});
document.getElementById("input1").style.borderColor = "red";
}
});
};
function insert_update_kpo_row() {
$.confirm({
attachOnlyOnce: true,
type: 'orange',
boxWidth: '39%',
useBootstrap: false,
theme: 'material',
icon: 'fa fa-warning',
title: 'font-awesome',
title: 'Warning?',
content: 'Create KPO row??',
buttons: {
Yes: {
btnClass: 'btn-orange',
action: function () {
$.ajax({
url:"php/insert_order_row_to_db.php",
method:"POST",
dataType:"json",
success:function(data){
$("#last_id_kpo").val(data);
inv_kpo_ajax(function result_kpo(data){
if(data == 1){
} else {
$('.alert-icon-4').removeClass('fa-check').addClass('fa-warning').css("background-color", "red");
$('#alert-popup-4').show(function() {
$('#alert-popup-4').addClass('alert-show');
$('#alert-popup-content-4').text('Allert KPO !!!');
});
document.getElementById("input1").style.borderColor = "red";
}
});
document.getElementById("input1").removeEventListener("blur", insert_update_kpo_row);
}
});
},
},
No: {},
},
});
};
});
I need that when input1 triggers blur that the first ajax runs with confirm to insert a row into the DB.
If a duplicate exists it should show the Alert popup and let it stay on screen.
And even if after this the input1 is changed to a Successful popup one can get back to this input1
and enter numbers for which there exists a duplicate in the DB. Then the Alert should display but without a confirm popup to create a row.
In my current situation when the first blur happens on input1 the popup div shows and immediately hides.
How can I fix this behaviour?
I have the following html:
<div class="modify">
Change<br>
Delete
</div>
And an according jQuery:
$(".delete").click(function(){
var parent_element = $(this).closest('li');
var url_string = $(this).attr('id') + '/delete/';
$.ajax({
type: 'POST',
url: url_string,
success: function(response) {
parent_element.fadeOut(600, function() {
parent_element.remove();
});
}
});
});
Now I want to ask the user for confirmation within .modify. The current contents .change and .delete should disappear and be swapped for something like:
Are you sure?
Yes
No
This is how it would look in general:
If the user presses Delete the contents should change like this:
As you might have figured, if the user chooses
Yes, the parent_element should be deleted
No, .modify should return back its original state
What would be the idiomatic way to do this?
I modified my answer after your additional note.
codepen live example
What about..
HTML
<div class="modify askState">
<div class="ask">
Change<br>
Delete
</div>
<div class="confirm">
<span class="confirmDeleteText">Are you sure?</span><br/>
Yes
No
</div>
</div>
JS
var askState = true, modifyElement = $(".modify");
$(".delete").click(function(){
askConfirmation();
});
function askConfirmation() {
toggleState();
}
$(".confirmYes").click(function() {
var parent_element = $(this).closest('li');
var url_string = $(this).attr('id') + '/delete/';
$.ajax({
type: 'POST',
url: url_string,
success: function(response) {
parent_element.fadeOut(600, function() {
parent_element.remove();
});
}
});
});
$(".confirmNo").click(function() {
toggleState();
});
function toggleState() {
if( askState ) {
modifyElement. addClass("confirmState").removeClass("askState");
} else {
modifyElement.removeClass("confirmState"). addClass("askState");
}
askState = !askState;
}
CSS
.confirmState .ask {
display: none;
}
.askState .confirm {
display: none;
}
I added HTML so that the original text wont get lost (if you do innerHTML=newText then you cannot restore its innerHTML properly without backing up).
Please also note that its fairly readable:
IF I click "delete", then ASK confirmation (semantic code).
IF I ask confirmation, then CHANGE State (functional code, could have been nice to make toConfirmState() in stead of toggleState()).
(then in new state)
IF I click "confirmYes", then DO perform code (functional code, could have been nice to make a delete function (semantic code))
$(".delete").click(function(){
var ans = confirm("Are You Sure To Delete This Record...");
if(ans)
{return true;}
else
{return false;}
... ur code so on
}
I am using this script from: http://pop.seaofclouds.com/
The problem is if you call the script multiple times it causes a cascading effect of a pop-out within a pop-out for as many times as you call the script.
I'm trying to figure out how to prevent it from executing when the popout has already been set. Here's the script:
//
// pop! for jQuery
// v0.2 requires jQuery v1.2 or later
//
// Licensed under the MIT:
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright 2007,2008 SEAOFCLOUDS [http://seaofclouds.com]
//
(function($) {
$.pop = function(options){
// inject html wrapper
function initpops (){
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
}
initpops();
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });
$("body").on("click", ".pop", function(){
closeInactivePop();
});
// toggle that pop
$("body").on("click", ".pop_toggle", function(){
$(this).parent(".pop").toggleClass("active");
});
}
})(jQuery);
now when i load this script on an ajax call the new pop-out menus work but the old ones do not react to the onclick event.
You shouldn't mess with the plugin. It works exactly like it should.
Better show us how you call this on elements that you already have.
Also I don't like this plugin. Better use something from JqueryUI
You can do such thing in much easier way.
[edit]
I tried your first code (the plugin) and it works correctly for me.
[edit]
OK. I get it. You call $.pop(); multiple times. You shouldn't! Calling $.pop(); will pin up the drop down menu to all elements that has class="pop". This is the reason why you have such funny stack.
Just use $.pop(); once.
Plugin doesn't give ability to connect NEW elements that was dynamically created on the page.
Removed pop from ajax call and just called this on success:
$(".pop").each(function() {
var pop_classes = $(this).attr("class");
if ( $(this).find('.pop_menu').length) {
// do nothing
} else {
$(this).addClass("pop_menu");
$(this).wrap("<div class='"+pop_classes+"'></div>");
$(".pop_menu").attr("class", "pop_menu");
$(this).before(" \
<div class='pop_toggle'></div> \
");
}
});
// assign reverse z-indexes to each pop
var totalpops = $(".pop").length + 100;
$(".pop").each(function(i) {
var popzindex = totalpops - i;
$(this).css({ zIndex: popzindex });
});
// close pops if user clicks outside of pop
activePop = null;
function closeInactivePop() {
$(".pop").each(function (i) {
if ($(this).hasClass('active') && i!=activePop) {
$(this).removeClass('active');
}
});
return false;
}
$(".pop").mouseover(function() { activePop = $(".pop").index(this); });
$(".pop").mouseout(function() { activePop = null; });
I made a method for my UI class that clears inputs in a containing div.
The problem is, once it is called, The checkboxes never get set through AJAX calls until you refresh the page. The example below is for my group/user management. If you click on a group to edit, a jQuery UI dialog pops up with the attributes and permissions of that group. If you cancel, and try to add a new one, the inputs are cleared. If you then goto edit a group after that, the inputs are not updated.
Edit: It seems the checkboxes stop working if the cancel button is clicked regardless if my clearInputs method is called or not.
Here is the method of the UI class:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
And an example of the calling code (copied from my project, but I cut some of the fat out...
/* The user clicks the edit group button... */
$(document).delegate('.group_edit', 'click', function() {
var groupId = $(this).attr('id').replace("group_edit_", "");
// This call to the clearInputs method is commented out,
// and behaves as I described above.
// ui.clearInputs("#dialogGroup");
$.ajax({
type: "POST",
url: "ajax.users.php",
data: {
action: "get_privs",
group: groupId
},
success: function (result) {
if (result.success == true) {
// Set the name value
$("#name").val(result.GroupName);
// Update each of the checkboxes
$.each(result.privs, function(priv, grant) {
grant = Boolean(parseInt(grant));
$('#dialogGroup input[value=' + priv + ']').prop('checked', grant);
});
/* Create the dialog */
$("#dialogGroup").dialog({
buttons: {
"OK" : function () {
$(this).dialog("close");
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Saves the form data */
});
},
"Cancel": function() {
ui.clearInputs("#dialogGroup");
$(this).dialog("close");
}
}
});
And finally to add a group:
$(document).delegate('#group_add', 'click', function() {
var dialog = "#dialogGroup";
// ui.clearInputs(dialog);
$(dialog).dialog({
modal: true,
title: "Create Group",
buttons: {
"OK": function() {
$(this).dialog("close");
$("#dialogNotify").html("Saving...");
$("#dialogNotify").dialog('open');
var form_data = new Array();
$.each($("input[#name='cbox[]']:checked"), function() {
form_data.push($(this).val());
});
$.ajax({
/* Save the form data */
});
},
Cancel: function() {
$(this).dialog("close");
}
}
});
});
I hope I included everything... If not I will update.
try this:
$( document ).ready(function()
{
var search_on = $('#formX');
$( search_on )
//CHANGE "input" for "input,select" to search all fields
.find('input')
.each(function( e )
{
if( $(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox' )
{
$(this).attr('checked',false);
//USE RESET() IF IS A FORM FIELD
$(this).reset();
}
//IF IS A DROPDOWN
/*
else if( $(this).attr('type') == undefined )
{
$(this).find('option').attr('selected',false);
}
*/
else
{
$(this).val('');
//USE RESET() IF IS A FORM FIELD
//$(this).reset();
}
});
});
Or use this function( if is a form ):
jQuery.fn.reset = function () {
$(this).each (function() { this.reset(); });
}
And Call
$('#formX').reset();
I figured it out. The problem was inside of my method, I had:
clearInputs: function(container) {
$(container + " :input").val("");
$(container).find('input[type=checkbox]:checked').prop('checked', false);
}
The first line of the method, I guess is doing something to all inputs.
If you change the first line to
$(container + " :input[type=text]").val("");
It works fine...
I am developing the MooTools confirm box function. In which I have two buttons which are OK and CANCEL.
So I want return TRUE on click of OK and return FALSE on click on CANCEL.
Here is my function code.
function confirm_box(title, text)
{
var className = 'msgAlert info';
var defaut_title ='Information';
// Placing the Overlay
var overlay = new Element('div', {'class':'msgAlert_overlay'});
$$('body').adopt(overlay);
// Placing the Main Div With class name
var main_box = new Element('div', {'class': className});
$$('body').adopt(main_box);
var content_div = new Element('div', {'class':'msgAlert_popup'});
//
if(title == '')
title=defaut_title;
content_div.set('html','<div class="msgAlert_header"><h4>'+title+'</h4></div><div class="msgAlert_content">'+text+'</div>');
main_box.adopt(content_div);
content_div.getChildren('a.msgAlert_close');
var footer_div = new Element('div',{'class':'msgAlert_footer'});
var ok_btn = new Element('button');
ok_btn.addEvent('click', function(){
main_box.fade(0);
//overlay.fade(0);
(function(){main_box.dispose(); overlay.dispose(); }).delay(350);
return true;
});
var cancel_btn = new Element('button');
cancel_btn.addEvent('click', function(){
main_box.fade(0);
//overlay.fade(0);
(function(){main_box.dispose(); overlay.dispose();}).delay(350);
return false;
});
ok_btn.set('html','Ok');
cancel_btn.set('html','Cancel');
footer_div.adopt(ok_btn);
footer_div.adopt(cancel_btn);
main_box.adopt(footer_div);
ok_btn.focus();
}
I have placed return TRUE and FALSE on click on respective buttons.
Can any suggest in which way I have to go so I can access my function just like the JS confirm box:
Just Like :
if(confirm_box(title, text))
{
alert('Yes');
}
else
{
alert('No');
}
this is not going to work. basically, you can use the native
if (confirm("are you sure")) { ... } else { ... }
which is fine, because it is blocking the UI thread...
when you want to replicate a confirm box, you need to work with an event callback method instead as your function will NOT have a return value.
in pseudo code, this will be:
var confirm_box = function(title, text, onConfim, onCancel) {
...
confirmEl.addEvent("click", onConfirm);
cancelEl.addEvent("click", onCancel);
};
confirm_box("Are you sure?", "Please confirm by clicking below", function() {
alert("yes");
}, function() {
alert("no");
});
in the context of mootools and Classes, you may want to do a confirm class which works with events instead. If you want an example, give me a shout.