Alert Box with specific functionality - javascript

I am getting a JS Alert-box When I am leaving my tabs 1st time.
But would like to get it as windows alert - any idea on basis of my code.
Also that should have a OK and Cancel Button - Ok > Next Tab
Cancel> Same tab
$(document).ready(function () {
B.initB();
var 3firstTimeMsg = true;
var 4FirstTimeMsg = true;
$(".3a-tab").click(function(){
if(3firstTimeMsg == true)
{
alert("If you leave this page, any information you've entered will be lost.");
3firstTimeMsg = false;
}
});
$(".3b-tab").click(function(){
if(4FirstTimeMsg == true)
{
alert("If you leave this page, any information you've entered will be lost.");
4FirstTimeMsg = false;
}
});
});

That would probably be a confirm box:
if(3firstTimeMsg == true) {
3firstTimeMsg = confirm("If you leave this page, any information you've entered will be lost.");
}
FIDDLE

Related

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

Prevent Javascript confirm() on Checkbox State Change

I have a checkbox (which uses the Bootstrap Switch library to act as an on/off toggle) to activate and deactivate users with the help of AJAX.
When a user unchecks the box this function is fired:
$('.user-status-ckbx').on('switchChange.bootstrapSwitch'...
The confirm() dialog pops up asking the user if he's sure he wants to de/activate the user. If the user clicks 'NO', the button is sent back to its original state using:
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
The problem I am having is that each time the toggleState() runs, the switchChange.bootstrapSwitch also runs again. This sents up a non-ending confirm() message which only goes away if the user confirms the message.
Is there an efficient way to prevent the switchChange.bootstrapSwitch method from running based on a real user click vs. a programmatically-generated toggle?
I've already tried:
e.originalEvent !== undefined
and
e.which
as suggested in other similar questions, but none of those work, nor do they even appear in the 'e' object...
<script>
$(".user-status-ckbx").bootstrapSwitch('size', 'mini');
$(".user-status-ckbx").bootstrapSwitch('onText', 'I');
$(".user-status-ckbx").bootstrapSwitch('offText', 'O');
//ajax to activate/deactivate user
$('.user-status-ckbx').on('switchChange.bootstrapSwitch', function(e){
var currentDiv = $("#" + e.currentTarget.id).bootstrapSwitch('state');
if( currentDiv == false){
var confirmed = confirm("Are you sure you wish to deactivate this user? They will no longer be able to access any forms.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
} else {
var confirmed = confirm("Are you sure you wish to activate this user? Deactivated users which were previously active will have the same permissions prior to their de-activation unless changed manually.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
}
});
function changeActivationStatus(userId){
$.post("{{ path('isactive') }}", {userId: userId})
.done(function(data){
console.log("Finished updating " + userId);
})
.fail(function(){
console.log("User could not be updated");
});
};
</script>
There's a way to prevent the event when switching programmatically.
You have to add options to the Bootstrap switches:
var options = {
onSwitchChange: function (event, state) {
// Return false to prevent the toggle from switching.
return false;
}
};
$(".user-status-ckbx").bootstrapSwitch(options);
And when programmatically switching the button, you'll have to add a second argument:
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState', true);
JSFiddle: https://jsfiddle.net/Ravvy/npz8j3pb/
$(".uid-toggle").change(function (event) {
var option = confirm('Are you sure, you want to change status?');
console.log(`$(this).prop('checked')`);
if (option) {
} else {
if ($(this).prop('checked')) {
$(this).prop('checked', !$(this).prop('checked'));
$(this).parent().removeClass('btn-primary off');
$(this).parent().addClass('btn-danger off');
} else {
$(this).prop('checked', !$(this).prop('checked'));
$(this).parent().addClass('btn-primary off');
$(this).parent().removeClass('btn-danger off');
}
}
});

How to tell if a radio button is left unchecked with Javascript/JQuery

I am creating a quiz/survey form with jQuery and javascript and I am having some trouble with the question validation.
The way the quiz/survey creation works is a series of show/hides display relevant form fields. The user fills out one set of fields for the first question and then they are asked if they would like to add another question to their quiz/survey and the next set of form fields is displayed.
I am struggling because instead of having a massive validation when the user has completed all of their possible form fields I am running a validation script at the end of each question with the associated form field IDs and values being passed into the script upon the user completing that question. This script is below, but some key areas of the script are based upon whether radio buttons have been checked. For instance if the user has left the question text area empty they are alerted to fill in question text, or if they select a true/false answer or multiple choice answer, they are supposed to determine which is the correct answer based upon a radio button list. Here is the entire validation code:
var questionValidate = function(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID) {
// alert(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID);
if (jQuery('select[name="CAT_Custom_14"]').val() == 'Quiz') {
if (jQuery(qTextID).val() == "") {
var qText = true;
alert('Question Text field is blank!');
};
if (jQuery(qAnswerType).val() == " ") {
var answertype = true;
alert("There's no answer selected.");
} else if (jQuery(qAnswerType).val() == 'True/False') {
if (jQuery(TFID).attr("checked") == true) {
var tfanswer = true;
var mcanswer = false;
alert('True False is selected');
} else if (jQuery(TFID).attr("checked") == false) {
alert('True False is not selected.');
};
} else if (jQuery(MCID).attr("checked") != 'checked' ) {
var mcanswer = true;
var tfanswer = false;
alert('The correct Multiple Choice Answer is not selected');
if (jQuery(MCText1).val() == "" || jQuery(MCText2).val() == "" || jQuery(MCText3).val() == "" || jQuery(MCText4).val() == "") {
var mcTextfields = true;
alert("There are Multiple Choice Fields that you have left blank.");
} else {
mcTextfields = false;
};
};
if (jQuery(VisRef).val() != " ") {
if (jQuery(VisRef).val() == "Youtube Video" && jQuery(Youtube).val() == "") {
youtubeVal = true;
alert('Please enter your Youtube Video code.');
} else if (jQuery(VisRef).val() == "Vimeo Video" && jQuery(Vimeo).val() == "") {
vimeoVal = true;
alert('Please enter your Vimeo Video code.');
} else {
validateImage(ImgID);
};
} else {
youtubeVal = false;
vimeoVal = false;
tempImgCheck = false;
}
};
};
I have run into a way to tell whether the radio button is checked, however it does not appear to be working with my script the way that I want it to. If you look at this area of the code you should be able to see that it first determines the answer type (true/false or multiple choice) and then if the correct answer is not selected the user should be alerted. So if they do not select the 'true', 'false', 'a', 'b', 'c', or 'd' radio button the validation should alert them to select it.
If there are any other ways to check if the correct radio buttons are selected I would appreciate anyone's help in figuring this out.
Thank you so much!
I think you want something like this:
if($('#radio_button').is(':checked')){
alert("I am checked");
}
You could check for a button that isn't checked by negating that statement.
if(!$('#radio_button').is(':checked')){
alert("I'm not checked");
}

Javascript How to trigger a function when we User Tries to Exit or Refresh the Page

When a user tries to exit the page after reading price of the product, i want to offer them 1st discount.
If they select 'YES' they buy the product instead of closing the window, if they select 'NO' then i would make 2nd discount
offer and this time it will be the last offer.
If they click 'NO' again even second time, his browser will
close or else he would buy the product at the given 2nd discount
price.
My Example is illustrated below:
<script type="text/javascript">
function getOffers()
{
var question1 = confirm("Wait! we are now offering this Product in $25.00, buy it?");
if(question1 == 'true')
{
alert('You have purchased this product for $25.00');
}
else
{
var question2 = confirm("Wait! we would like to make one Final Offer, price of Product in $15.00, buy it?");
if(question2 == true)
{
alert('You have purchased this product for $15.00');
}
else
{
//Close this window
}
}
}
</script>
My question is, how can i trigger this function when user tries to exit (or) refresh the page.
Additional INFO:
I have rewritten the code and trying to fix the annoying page load popup, can any one suggest me on this?
<script type="text/javascript">
function getOffers()
{
//alert(firrsTime);
if(firstTime == 'no')
{
var question1 = confirm("Wait! we are now offering this Product in $25.00, buy it?");
if(question1 == 'true')
{
alert('You have purchased this product for $25.00');
}
else
{
var question2 = confirm("Wait! we would like to make one Final Offer, price of Product in $15.00, buy it?");
if(question2 == true)
{
alert('You have purchased this product for $15.00');
}
else
{
//Close this window
}
}
}
}
window.onunload = function(){
firstTime = 'no';
getOffers();
}
window.onload = function(){
firstTime = 'yes';
getOffers();
}
</script>
I am trying to pass a global variable 'firstTime' to check if it is from onLoad then dont display offer if it is from onUnload then display offer. Is there any solution on this problem?
<body onunload="OnUnload()">
then
function OnUnload()
{
//put code here
}
Use the onunload and onload.
window.onunload = function(){getOffers();}
window.onload = function(){getOffers();}
Though it will show it when user first loads the page, so i wouldn't recommend on doing that.
About the way to distnguish between First load and refresh,
Have not tried this, but i found this code somewhere :
function OnCrmPageLoad()
{
//bind to the onsave event
crmForm.attachEvent(“onsave”,OnCrmPageSave);
if (crmForm.new_ispostback.DataValue == true)
{
//form was saved
//reset the field
crmForm.new_ispostback.DataValue = false;
}
}
function OnCrmPageSave()
{
// validate form if needed
crmForm.new_ispostback.DataValue = event.returnValue = true;
crmForm.new_ispostback.ForceSubmit = true;
return true;
}
Play around with it.

Javascript onbeforeunload close browser window

I have this tiny script for now that checks if any change is made on the form. If there is a change
then I set a flag to 'Y'. I call this function on onBeforeunload="changeConfirm()" places in the body tag. I know
I can't stop the user from closing down the window, but how do I make this scenario work where he made a change
-> decide to close the window -> Script alerted him -> User clicks cancel (Now I need to bring him back to the screen
instead of closing browser.
<script type="text/javascript">
var Flag= "";
function changeConfirm(){
if(Flag == 'Y')
{
var confirmStatus = confirm('Changes made. Dont want to save?');
}
else {
alert("No changes were made " + Flag);
}
}
</script>
Try this :
function confirmChanges() {
if(Flag == 'Y')
{
if(confirm('Changes made. Dont want to save?')){
return false;
}else{
return true;
}
}
else {
alert("No changes were made " + Flag);
}
}
It should be like this:
window.onbeforeunload = function() {
if ( Flag == 'Y' ) {
return "Changes made. Don't want to save?";
}
}

Categories