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");
}
});
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 done an auto complete such that when I click the selected result it appends to a div.
image when picking a vehicle
But when I navigate away from that popup and return to it. When I do a search and click the result I want, it appends two values at a go with the second one as empty like in the next image.
the second image with a blank value
How do I prevent this from happening ?
My code is as shown below:
$(function(){
$(".search1").keyup(function() {
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!=''){
$.ajax({
type: "POST",
url: "assets/ajax/search1.php",
data: dataString,
cache: false,
success: function(html){
$(".resultgeter").html(html).show();
}
});
}return false;
});
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
$('.search1').click(function(){
$(".resultgeter").fadeIn();
return false;
});
});
I don't know the real solution for this, but a trick might work.
Adding an if statement to make sure vhlid is not blank while appending.
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
if(vhlid!=" " || vhlid.length>1) {
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
}
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
I have a login form where we make an AJAX call to the server to perform a bit of validation before letting the login form continue submitting. The current code is outlined below:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
if (username.length <= 0) {
return false;
}
var userIsValid = false;
$.ajax({
async: false,
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
return userIsValid;
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
$(".loginButton").on("click", function (e) {
$errorMessageLabel.hide();
if (isUserValid($usernameTextbox.val())) {
return true;
} else {
$errorMessageLabel.show();
$errorMessageLabel.html(errorMessageHtml);
}
e.preventDefault();
return false;
});
})(jQuery);
I know that async: false is something that shouldn't be used since it's going out of style. My question is: What's the alternative. My click event handler needs to return true or false, meaning it has to wait for the ajax call to complete. If async: false is no longer an option, then the isUserValid method is going to return immediately without properly setting the userIsValid bool.
Now I can inline the ajax method call straight into the click event handler that's called on $(".loginButton"), but the same problem presents itself: It needs to either return true, or prevent default (i.e. prevent login) and return false depending on the result of the ajax call. Is there a way I can force the click event handler to wait for the result of the ajax call before returning, without using async: false? I understand there's a jQuery when() method, but I don't know if I can use that in this situation.
First thing, a form can be submited without clicking on respective submit button. So bind instead submit event to the form. Now depending ajax request result, you can submit the form, using e.g:
(function ($) {
var errorMessageHtml = "";
function isUserValid(username) {
$errorMessageLabel.hide();
if (username.length <= 0) {
return false;
}
var userIsValid = false;
// return the promise from ajax method
return $.ajax({
url: "/myAjaxCall?username=" + username
}).success(function (validationResult) {
userIsValid = validationResult.IsValid;
errorMessageHtml = validationResult.ErrorMessage;
}).fail(function () {
errorMessageHtml = "Error contacting server. Please try again.";
});
}
var $usernameTextbox = $("#UserName");
var $errorMessageLabel = $(".errorMessageContainer");
// "form:has(.loginButton)" or whatever more relevant selector
$("form:has(.loginButton)").on("submit", function (e) {
$errorMessageLabel.hide();
isUserValid($usernameTextbox.val())).always(function(validationResult ){
if(validationResult && validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(errorMessageHtml).show();
}
}.bind(this));
e.preventDefault();
});
})(jQuery);
A. Wolff's answer is the answer I accepted, but I wanted to share my final code solution based off their input as well as the various comments made back and forth.
(function ($) {
"use strict";
var $usernameTextbox = $("#UserName");
var $passwordTextbox = $("#Password");
var $errorMessageLabel = $(".errorMessageContainer");
$("form").on("submit", function (e) {
$errorMessageLabel.hide();
var username = $usernameTextbox.val();
if (username.length <= 0 || $passwordTextbox.val().length <= 0) {
return; // Server posts back with "username/password required" so we don't handle it here.
}
$.get("/myAjaxCall?username=" + username).done(function (validationResult) {
if (validationResult.IsValid) {
this.submit();
} else {
$errorMessageLabel.html(validationResult.ErrorMessage).show();
}
}.bind(this)).fail(function() {
$errorMessageLabel.html("Error contacting server. Please try again.").show();
});
e.preventDefault();
});
})(jQuery);
Working with a modal form that submits edited information via ajax post. The thing is, it submitted once the first time .. fire up the modal form again, then submit, and twice it goes and so on and so forth. Does anyone had this sort of experience before? Please help.
$("#editInfo").click(function () {
valform = ["realname","email"];
valneed = 2;
$('#smallModal .modal-body').empty();
$('#smallModal .modal-body').load('/profile.php?action=profile_edit_info');
$('#smallModal .modal-title').text('Edit Personal Information');
$('#smallModal').modal('show')
$('#smallModal').on('shown.bs.modal', function () {
$("#smallModal #profileeditinfoform").keydown(function(event){
if(event.keyCode == 13 && event.target.nodeName!='TEXTAREA')
{
event.preventDefault();
return false;
}
});
$("#realname_comment").hide();
$("#email_comment").hide();
$('#realname').bind("change", function() {
$('#realname').addClass("spinner");
var v_realname = verifyVar($('#realname').val(),'name');
displayVerify(v_realname,'realname');
});
$('#email').bind("change", function() {
$('#email').addClass("spinner");
var v_email = verifyVar($('#email').val(),'email');
displayVerify(v_email,'email');
});
$("#editinfo_submit_btn").click(function(event) {
event.preventDefault();
$('#loader').fadeIn();
formData = $("#profileeditinfoform").serialize();
var v_submit = submitEditInfo(formData);
verifySubmitEditInfo(v_submit);
$('#loader').fadeOut();
});
});
});
function submitEditInfo(data) {
var alldata = data + '&action=profileeditinfo';
return $.ajax({
type: 'POST',
cache: false,
data: alldata,
url: '/ajax/submit.php'
});
}
function verifySubmitEditInfo(ajaxCall) {
ajaxCall.success(function(realData) {
response = JSON.parse(realData)
if (!response.success) {
$.gritter.add({
title: response.title,
image: '/img/custom/fail.png',
sticky: false,
text: response.message
});
} else {
valform = [];
$("#submitdiv").hide();
$("#profileeditinfoform").find("input:text").val('');
$('#infodiv').slideUp(200).load('/divloader.php?req=profile_info').slideDown(200);
$.gritter.add({
title: response.title,
image: '/img/custom/success.png',
sticky: false,
text: response.message
});
$("#smallModal").modal('hide');
}
});
}
Every time you click, you're adding a new event handler:
$('#smallModal').on('shown.bs.modal' //...
Are you sure you want to do this on "click", or might it be better to set this up outside of the click handler?
In fact, you're binding event handlers as a response to other events all over this code. That's probably not a great idea, unless you unbind them once you're done.
You need to pull out your binders, you bind a new time every time the button is clicked! Only bind on load, not under button click event.
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
}