local.Storage redirect if false - javascript

I have a site that needs to verify like a cookie. but i want to use local storage since it is a mobile concept.
I know the item is set through a test but i cant get the page to redirect when it is not true.
<script language="javascript">
if (localStorage.getItem('itemVerified') = 'True') {
window.location = "success.html";
}
else {
alert("You are not able to enter this site!");
window.location = "error.html";
}
</script>

There may be two errors, the first of which is that your comparison string missing an = sign:
incorrect: if (localStorage.getItem('itemVerified') = 'True') {
Correct: if (localStorage.getItem('itemVerified') == 'True') {
The second case is if you're looking to check the site from which to load the document you need to add the action to an event listener for them you can do the following.
<script type="text/javascript">
var verifyCookie = function(){
if (localStorage.getItem('itemVerified') == 'True') {
console.log("All right");
window.location = "success.html";
}
else {
alert("You are not able to enter this site!");
window.location = "error.html";
}
};
window.addEventListener ('DOMContentLoaded', verifyCookie, false);
</script>
Regards.

Related

why wouldn't either of document.location or window.location work?

This is the event handler I set up on a button:
$('.tabsTD').on('click', 'a.finalSave', (function () {
var returnStatus= finalSave(this, location);
if (returnStatus) {
if ($(this).text() == "Save and Continue") {
sessionStorage.carePlanReload = "true";
sessionStorage.activeTab = $('#tabs').tabs("option", "active");
window.event.returnValue = false;
document.location.reload(false);
}
else if ($(this).text() == "Save and Close") {
window.event.returnValue = false;
document.location = "MemberHome.aspx";
//setTimeout(function () { document.location = "MemberHome.aspx"; }, 500);
//return false;
//$('#aRedirectToHome')[0].click();
return false;
}
} /*END if*/
}));
In the else if condition, I need to redirect to "memberhome.aspx", but nothing seems to work. I also tried adding an anchor tag, like:
RedirectToHome
and then invoke a click on the anchor from else if, but it proved to be a failed attempt.
Please help.
You need to either pass a new value to the href property as in:
window.location.href = "MemberHome.aspx";
or, using assign method as in:
window.location.assign("MemberHome.aspx");

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

combine checkbox alert function with detect function

the goal here is to detect if a user is checking out on my site and then prompt them with a special alert if they uncheck a box.
how do i combine to two functions to do this?
the detect function so far is this
var pathArray = window.location.pathname.split('/');
if (pathArray.length >= 3) {
if (pathArray[1].toLowerCase() == "commerce") {
var page = pathArray[2].toLowerCase();
if (page.indexOf("show-cart") == 0) {
console.log("Detected the cart page."); // This works
} else if (page.indexOf("checkout") == 0) {
console.log("Detected the checkout page."); // Does not work (no injection)
} else if (page.indexOf("order-confirmed") == 0) {
console.log("Detected the order confirmation page."); // Does not work (no injection)
}
}
}
and the checkbox alert function is this:
function validate() {
var checkoutHistory = document.getElementById('shipToBilling');
if (checkoutHistory.checked) {
} else {
alert("You have elected to turn off checkout history.");
}
}
window.addEventListener("load", validate, false);
Your onclick function can call both your functions

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?";
}
}

How redirect cancel function in Javascript

I'm not a programmer. I don't want to protect with a strong secure code my page. I just need one option I'm missing in my code and can't figure out how to add it.
<script language="Javascript">
<!--
var password = "lala"
var x = prompt("","")
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
//-->
</script>
As you can see it's so dump but I need it. When I press Cancel button instead of writing true or false text, website still opens. I want to include in this script cancel button function (control it, you know) whitch would redirect to another website if press on it (as it is with true or false functions). I don't want to creat a special button or an input for it.
Update: I would like to include this script in a page which i am redirecting to. Could anyone tell me:
1. How can i modify this script to make it work only once?
2. Is it anything to do with browser's cookies?
p.s. Done :)
If the user presses cancel, prompt will return null. So do like this:
if(x == null) // Cancel
{
alert('Cancel');
}
else if (x.toLowerCase() == password) { // Correct password
location = "http://google.com";
}
else { // Wrong password
alert("Fail")
location = "http://facebook.com"
}
However, I'm not sure if all browsers will return null when the user presses cancel. (I have tested in Opera)
Try
var x = prompt("","");
if( x == null || x == '')
return;
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
To redirect your browser to a URL use following snippet in your Javascript:
top.location.href = "http://google.com";

Categories