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?
Related
I'm making a Blackjack game to exercise my Javascript skills. I had a bunch of alert() messages tied to the betting function to prevent invalid entries. In updating the code to have a more elegant message style than a browser alert, I wrote a function called alertModal() that pops up a message on the screen and then fades away. The message pops up the first time a user tries to enter an invalid bet, but does not pop up any other messages if the bet is invalid-- nothing happens. I know the placeBet() function is still running when the user clicks again, because if the bet is valid, dealFirstCards() runs and the game proceeds. So it seems to me that for some reason, the if/else portion of the placeBet() function is only running on the first click...
The game is live and running with this code at http://cnb-blackjack.netlify.com/game.html
Here is the javascript code in question:
// Player places a bet
$('div.bet').on('click', function() {
$(this).removeClass('glow');
$('.bet-button').addClass('glow');
});
$('.bet-button').on('click', function() {
event.preventDefault();
if (!placeBet.called) {
placeBet();
}
});
// PLACE BET
function placeBet() {
var $bet = parseInt($('.bet-input').val())
var $bank = parseInt($('.player-bank').text())
var $currentBet = $('.current-bet');
if (!isNaN($bet) && $bet <= $bank && $bet !== 0) {
$currentBet.text(' $' + $bet);
$('.bet input[type="text"]').val('');
$('.place-bet .hideaway').slideUp();
$('.player-bank').text($bank - $bet);
placeBet.called = true;
dealFirstCards();
} else if ($bet > $bank) {
var $message = 'Bet cannot exceed the amount in your Bank!';
alertModal($message);
} else if (isNaN($bet)) {
var $message = 'Enter a number, without "$".';
alertModal($message);
} else if ($bet === 0) {
var $message = "Betting nothing won't get you very far...";
alertModal($message);
}
}
// SHOW MODAL
function alertModal(message) {
$popUp = $('.alert-message');
$('.modal').removeClass('hide');
$popUp.text(message);
setTimeout(function() {
$('.modal').fadeOut(1000);
}, 1000);
}
function alertModal(message) {
$popUp = $('.alert-message');
$('.modal').show();
$popUp.text(message);
setTimeout(function() {
$('.modal').fadeOut(1000);
}, 1000);
}
As comments have explained, fadeOut is leaving the modal hidden after the first time it's clicked. Just call $(element).show(); on the modal to show it again and let fadeOut remove it.
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");
}
});
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 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;
}
});
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...