Ask for confirmation in the same div by swapping its contents? - javascript

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
}

Related

Incorrect flow of events using FlightJS

I am trying to figure out an issue where a specific div is showing up before an event being fired, specified by FlightJs functions.
define([
'flight',
'mixins/form'
], function(flight, formMixin) {
function forgotPasswordForm() {
this.attributes({
submitButtonSelector: '.btn-submit',
formSelector: '#forgot-password',
successMessageSelector: '.success-message',
successMessageEmailSelector: '.success-message span.success-email',
emailInputSelector: '#forgot-password #email',
errorSelector: '#forgot-password .error-message'
});
this.after('initialize', function() {
this.on('click', {
'submitButtonSelector': this.onSubmitButtonClicked
});
this.on('keyup keypress', {
'formSelector': this.onFormKeyUp
});
});
this.onFormKeyUp = function(event) {
// Capture and deal with "Enter" key being pressed.
var keyCode = event.keyCode || event.which;
if (keyCode == 13) {
event.preventDefault();
this.onSubmitButtonClicked();
return false;
}
};
this.onSubmitButtonClicked = function(event) {
var email = this.select('emailInputSelector').val();
if (email.length > 0) {
this.select('errorSelector').hide();
this.postForm(this.select('formSelector'))
// Show success message on error to hide malicious password resetting.
.error(this.showSuccessMessage(email))
.done(this.showSuccessMessage(email));
} else {
this.select('errorSelector').show();
}
};
this.showSuccessMessage = function(email) {
this.select('successMessageSelector').show();
this.select('successMessageEmailSelector').text(email);
};
}
flight.component(forgotPasswordForm, formMixin).attachTo('.forgot-password-form');
});
As you can see, after detecting initialization, I specified the on click event for onSubmitButtonClicked.
In the onSubmitButtonClicked function I collect the field value and pass it to Request handler specified in the mixin 'form' which looks like this:
define([], function() {
'use strict';
function formMixin() {
/*
* Use an existing form to post data asynchronously, in order to avoid
* hard coding URLs and data transformation on Javascript.
*/
this.postForm = function($form) {
return $.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
});
};
}
return formMixin;
});
The issue is that the showSuccessMessage() function is being fired off right after initialization rather that after waiting for Submitbuttonclicked. Is the chaining of the callbacks of error and done incorrect or is there something else wrong with the code ?
Assuming that you have a working require.js / webpack config somewhere, you are not using any CSS class to hide the message elements and your markup looks something like this:
<div class="forgot-password-form">
<form id="forgot-password" method="GET"
action="https://jsonplaceholder.typicode.com/comments">
<input id="email">
<div class="error-message">
Error!
</div>
</form>
<button class="btn-submit">
Submit
</button>
<div class="success-message">
Success!
</div>
</div>
I would say you are only missing to hide the message elements in the initialize event.
It should look something like this:
// ...
this.after('initialize', function() {
this.on('click', {
'submitButtonSelector': this.onSubmitButtonClicked
});
this.on('keyup keypress', {
'formSelector': this.onFormKeyUp
});
this.select('successMessageSelector').hide();
this.select('errorSelector').hide();
});
// ...
I made a fiddle where you can have a look.

How to make 2 condition in button clicked jquery

Hello is that possible to make two condition from 1 button clicked?
if(unable == 4) {
$("#formitem").submit(function () {
$("#order_4").appendTo("body");
var message = "<?=$message_change_location?>";
var resotid = <?=$restaurant_info["restaurant_id"]?>;
var restoname = "<?=$restaurant_info["restaurant_name"]?>";
var restomenu = "<?=$restaurant_menu?>";
var postal = "<?=$postal?>";
var delivery_no = "<?=$delivery_no?>"
jQuery.ajax({
type: "GET",
url: "/ajax/order_unable",
dataType: 'html',
data: {
message_change_location: message,
restid: resotid,
restname: restoname,
restmenu: restomenu,
postal: postal,
delivery_no: delivery_no,
},
success: function (res) {
$("#order_4_show").html(res);
$("#order_4").modal("show");
}
});
return false;
});
}else if($("#second_notif") == "show"){
$("#formitem").submit(function () {
alert("asdf");
});
I want to make a condition if second_notif is showed, than if i click $("#formitem") for the second times will show the alert. The first click will show pop up windows, and there is not any problem here.
in the pop up windows there is a script to show the second_notif, with this following code :
<script>
$(document).ready(function() {
$("#change_location_2").click(function () {
$(".vendor-heading").hide();
$(".location-header").hide();
$("#order_4").modal("hide");
$("#second_notif").show();
return true;
});
});
</script>
and there in same page on where to show the pop up windows there is a code to show the second_notif too :
$("#change_location").click(function(){
$(".vendor-heading").hide();
$(".location-header").hide();
$("#second_notif").show();
return true;
});
here is the view for the second_notif :
<div id="second_notif" style="display:none;">
<?php $this->load->view('MAIN/'.country_code.'/search');?>
</div>
I can show the pop up windows, and show the second_notif when i clicked formitem button, but when the second_notif has been showed and if i clicked the same button again, why i cant show the alert?
guys can you help me how to show the alert?
p.s alert is not my goal, i will change the alert to other view
please help me guys, thank you (:
First of all, you only need one event handler for this method. You can then move your conditionals into the handler.
Secondly, your condition $('#second-notif') == 'show' will not work, as is will never evaluate to true. To test if an element is visible using jQuery, use the .is(':visible') method. Here's a quick example of what you're looking for:
JSFiddle
Bind the two element in single handler
$("#change_location_2, #change_location").click(function () {
$(".vendor-heading").hide();
$(".location-header").hide();
$("#order_4").modal("hide");
$("#second_notif").show();
return true;
});
how if you add condition to form submit like this ?
$("#formitem").submit(function () {
if(unable == 4) {
$("#order_4").appendTo("body");
var message = "<?=$message_change_location?>";
var resotid = <?=$restaurant_info["restaurant_id"]?>;
var restoname = "<?=$restaurant_info["restaurant_name"]?>";
var restomenu = "<?=$restaurant_menu?>";
var postal = "<?=$postal?>";
var delivery_no = "<?=$delivery_no?>"
jQuery.ajax({
type: "GET",
url: "/ajax/order_unable",
dataType: 'html',
data: {
message_change_location: message,
restid: resotid,
restname: restoname,
restmenu: restomenu,
postal: postal,
delivery_no: delivery_no,
},
success: function (res) {
$("#order_4_show").html(res);
$("#order_4").modal("show");
}
});
return false;
}else if($("#second_notif") == "show"){
alert("asdf");
}
});

Inserting a Confirm/Cancel pop-up into JQuery - CSS Issue

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;
}
});

jquery .on() is not triggering

I have the following code:
console.log($(".resultLike"));
$(".resultLike").on("click", function (event) {
alert('test');
event.stopPropagation();
alert('test1');
value['clicked'] = 1;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'removed') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Favourite?');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Login to add');
} else {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('un-Favourite');
}
}
});
});
My expectations is that when you click on the div resultLike, then it will preform the function(). However, it does nothing. I have two alert() calls in there, and neither is being called. The output of console.log() is as follows:
[
<div class=​"resultLike searchBarGameLike">​</div>​
]
That proves it's being put on the page. Any help would be appreciated, thanks.
EDIT:
I think it should be mentioned that I'm actually using two .on() events.
This is actually all my code. The issue is around the
$("body").on("click", ".resultLike", function(){
Line, it's not working.
$searchedGamesContainer.on(
"click",
".box",
function(event){
if(!$displayLock){
$displayLock = true;
var description;
var user_id;
if($(this)[0].style.width == '75%'){
var org_img = $(this).children(".resultInside").find("img").attr("src");
$(this).children(".resultInside").append("<img src='"+org_img+"' id='imgId'/>");
$(this).children(".resultInside").css('height','auto');
$(this).css('width', '18%');
$(this).css('height', 'auto');
$(this).find(".resultData").fadeOut('fast');
setTimeout(function(){$searchedGamesContainer.masonry('reload');},300);
setTimeout(function(){$displayLock = false;},1000);
}else{
var me = this;
var pos;
largeImage= new Image();
value['name']=$(me).find("p").html();
oldImage = $(this).find("img").attr("src");
for(var i = 0; i<$searchBarGames.length; i++){
if($searchBarGames[i][5] == value['name']){
pos = i;
break
}
}
description = $searchBarGames[pos][2];
$(me).find("img").hide();
largeImage.src = $searchBarGames[pos][4];
$(me).find("img").attr("src",largeImage.src);
$(me).children(".resultInside").css('height','400px');
$(me).css('width', '75%');
$(me).children(".resultInside").html("\
<div class='resultData'>\
<div class='resultImg'><img src='"+ largeImage.src +"'></div>\
<div class='resultName'>" + value['name'] + "</div>\
<div class='resultDesc'>" + description +"</div>\
<div class='wikiLink searchBarGameWiki'><a href='http://wikipedia.org/wiki/" + value['name'] + "'>Wikipedia</a></div>\
<div class='resultLike searchBarGameLike'></div>\
</div>");
value['clicked']=0;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
console.log($(".resultLike"));
$("body").on("click", ".resultLike", function(){
alert('test');
event.stopPropagation();
alert('test1');
value['clicked']=1;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
}
);
}
}
}
);
try
$("body").on("click", ".resultLike", function(){
// your code goes here.
});
Your implementation will likely not be bound if the div.resultLike is added dynamically
This problem actually ended up being completely because of CSS.
For the div element I wanted the alerts on, I had markup to look like a button.
However, I noticed this:
.resultLike:active {
position:relative;
top:1px;
z-index:1235;
}
I'm not 100% why, but I think this was actually changing where the button was when clicking it. Meaning as soon as it was active, it wasn't where your mouse was. I could be wrong, but this fixed it.

Jquery and CSS preforming strangely

I've this section of code (I'll point out where I'm confused, just added that huge wall to incase anyone wanted to really dig in).
anyway, the behaviour is to display these boxes, when you click on a box, the box expands, and displays more information. this works 70% of the time, however, it seems when an image is not chached, when you click the box again to minimize it, it starts to minimize, then pops back out. I'm wondering if this has something to do with the line: if($(this)[0].style.width == '70%'){
If this isn't enough, feel free to ask, and if you want to attempt to replicate the issue:
http://newgameplus.nikuai.net/
Try searching a few games, and clicking on the results. (That's only if what I"m saying isn't making sense though)
Thank you.
$container.on("click", ".box", function (event) {
var description;
var user_id;
var org_img = $(this).find("img").attr("src");
if ($(this)[0].style.width == '70%') {
$(this).find("img").attr("src", org_img);
$(this).css('width', '18%');
$(this).find(".resultData").fadeOut('slow');
$container.masonry('reload');
} else {
var me = this;
value['name'] = $(me).find("p").html();
oldImage = $(this).find("img").attr("src");
$.ajax({
url: 'scripts/php/fetchResultsData.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (data) {
description = data[0][2];
for (var i = 0; i < $test.length; i++) {
if ($test[i][1][2]['name'] == value['name']) {
pos = i;
break;
}
}
$(me).find("img").attr("src", data[0][4]);
$(me).css('width', '70%');
$(me).append("\
<div class='resultData'>\
<div class='resultName'>" + value['name'] + "</div>\
<div class='resultDesc'>" + description + "</div>\
<div class='reasonDataTitle'> Similar tropes between this game and the searched games </div>\
<div class='reasonData'>" + $test[pos][4] + "</div>\
<div class='wikiLink'><a href='http://wikipedia.org/wiki/" + value['name'] + "'>Wikipedia</a></div>\
<div class='resultLike'></div>\
</div>");
value['clicked'] = 0;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'alreadyAdded') {
$(me).children('.resultData').children('.resultLike').html('un-Favourite');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultData').children('.resultLike').html('Login to add');
} else {
$(me).children('.resultData').children('.resultLike').html('Favourite?');
}
}
});
$(me).on("click", '.resultLike', function (event) {
event.stopPropagation()
value['clicked'] = 1;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'removed') {
$(me).children('.resultData').children('.resultLike').html('Favourite?');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultData').children('.resultLike').html('Login to add');
} else {
$(me).children('.resultData').children('.resultLike').html('un-Favourite');
}
}
});
});
$container.masonry('reload');
}
});
}
});
I would suspect there's a race condition in your effects code. jQuery effects run asynchronously, so $container.masonry('reload') will get called when fadeOut starts rather than after it's finished. If the jQuery Masonry plugin affects the display of any blocks you're fading out (and its documentation indicates that's highly possible), that race condition of both functions running at once will cancel the first one out.
To work around this, try running the Masonry reload in a callback function to fadeOut, like so:
$(this).find(".resultData").fadeOut('slow', function () {
$container.masonry('reload');
});
The reason it happens only sometimes is based on the speed of how things are loading, which would explain why it only happens when certain assets aren't cached.

Categories