Fire remember me cookie only when user clicks checkbox - javascript

Updated Code: thank you for the suggestions so far. Still not working.
I'm trying to add a remember me cookie, but only when the user actually clicks the checkbox. Is this possible? I'm not having any luck with this code. The cookie fires regardless if the checkbox is clicked or not:
JavaScript:
<script>
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')) {
document.cookie="rememberme=yes;domain=.abc.com;path=/"
localStorage.usrname = $('#username').val();
localStorage.pass = $('#password').val(); localStorage.chkbx = $('#rememberme').val();
}
else {
document.cookie="rememberme=no;domain=.abc.com;path=/"
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
</script>
HTML:
<label class="checkbox" style="border: none;">
<input type="checkbox" value="rememberme" id="rememberme"> Remember me
</label>

Updated Code
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')){
document.cookie = "rememberme=yes;domain=.abc.com;path=/"
// save username and password
localStorage.usrname = $('#username').val(); localStorage.pass = $('#pass').val(); localStorage.chkbx = $('#rememberme').val();
}
else {
document.cookie = "rememberme=no;domain=.abc.com;path=/"
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});

tested below code in jsfiddle, hope it works as per your need. Please test it once, and let me know if its working as expected.
https://jsfiddle.net/arivua/xpvt214o/924480/
// set cookie value
function setCookie(key, value) {
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/";
}
// delete cookie
function deleteCookie(name) {
setCookie(name, "");
}
var remember_me_check_box = $("#rememberme")
// handle click and manage cookie
remember_me_check_box.on("click", function(){
if (remember_me_check_box.is(':checked')) {
deleteCookie('rememberme');
setCookie('rememberme', 'yes');
} else {
deleteCookie('rememberme');
setCookie('rememberme', 'no');
}
})

The solution was to just set "If" and "else" conditions around the URL that declares rememeberme. However the conditional URL is constructed (notice yes vs no) is handled by the back end folks where I am a front end UI developer.
<script>
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')) {
document.cookie="rememberme=yes;domain=.abc.com;path=/";
}
else {
document.cookie="rememberme=no;domain=.abc.com;path=/";
}
});

$('#rememberme').click(function () {
if ($('#rememberme').is(':checked')) {
document.cookie = "rememberme=yes;path=http://localhost:3000/login/"
var u = document.getElementById('email').value;
var p = document.getElementById('password').value;
var r = document.getElementById('rememberme').value;
document.cookie = "email=" + u + ";path=http://localhost:3000/login/";
document.cookie = "password=" + p + ";path=http://localhost:3000/login/";
}
else {
document.cookie = "rememberme=no;path=http://localhost:3000/login/"
document.cookie = "email=;path=http://localhost:3000/login/";
document.cookie = "password=;path=http://localhost:3000/login/";
}
});
function getcookiedata() {
var user = getCookie('email');
var pswd = getCookie('password');
var remember = getCookie('rememberme');
document.getElementById('email').value = user;
document.getElementById('password').value = pswd;
if (remember == 'yes') {
document.getElementById('rememberme').checked = true;
} else {
document.getElementById('rememberme').checked = false;
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
<input type="checkbox" name="rememberme" id="rememberme">&nbsp Remember Me<br>

Related

How to check if an element has a class using PHP in Wordpress function.php file

I am trying to hide an element on the front-end and remember the user choice by creating a cookie in PHP.
Here is how I have it set up:
I have some HTML and JS scripts inside an HTML widget on the page on the front-end
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
}
</script>
Then I have written the cookie function inside the function.php of the child theme:
add_action('init', function() {
if (!isset($_COOKIE['training_banner_cookie'])) {
setcookie('training_banner_cookie', 'showbanner', strtotime('+1 day'));
}
if (class_exists('hidebanner')){
?><style>#training-alert{display:none;}</style> <?php
setcookie('training_banner_cookie', 'hidebanner', strtotime('+1 day'));
}
$cookieValue = $_COOKIE['training_banner_cookie'];
if ($cookieValue == "hidebanner"){
?><style>#training-alert{display:none;}</style> <?php
}
});
For some reason, the class_exists() PHP function does not work, any idea how this can be achieved?
https://www.php.net/manual/en/function.class-exists.php
class-exists is not used in your case. It is used to check if a Class exists in your PHP code block.
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
What you want to do is to save the choice of the users' choice. You can simply use JS to achieve it.
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cookieName: string, cookie?: string): string {
const name = cookieName + '='
const decodedCookie = decodeURIComponent(cookie || document.cookie)
const ca = decodedCookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i]
while (c.charAt(0) === ' ') {
c = c.substring(1)
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length)
}
}
return ''
}
function setCookie(
cookieName,
value,
days,
isSecure = true
): void {
let expires = ''
const secure = isSecure ? '; Secure' : ''
if (days) {
const date = new Date()
date.setTime(date.getTime() + days * 86400000)
expires = ' ;expires=' + date.toUTCString()
}
document.cookie = cookieName + '=' + value + expires + ' ;path=/' + secure
}
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
setCookie('training_banner_cookie_hide', true, 1)
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide')
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
With the help of #WillyLi's answer, I was able to organize my thoughts and modify his code a bit here is what worked for me:
I modified the getCookie function declaration and simplified it to one parameter cname.
Then I also modified the setCookie and standardized it according to w3school
Finally, I wanted the banner to be hidden immediately as the user clicks the button so I added element.style.display = 'none'; to myFunction()
Here is what the final version looks like:
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function myFunction() {
var element = document.getElementById("training-alert");
element.style.display = 'none';
setCookie('training_banner_cookie_hide', true, 1);
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide');
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>

Delete specific cookie with Javascript

I need to delete a specific cookie from a website. At first I have tried several ways to delete ALL cookies, however none of them worked properly (not all cookies were deleted).
I also tried the below code to find the cookie I need to delete, but I can't figure out how to delete it after found it.
Can anyone help?
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
function deleteCookie() {
var myCookie = getCookie("dropin_date");
if (myCookie == null) {
}
else {
// if cookie exists delete it
}
}
deleteCookie();
check this out.
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var mycookie = accesCookie('test');
if(mycookie != ''){
delete_cookie('test');
}
In order to delete a cookie set the expires date in the past. it will delete automatically

JavaScript Compiler Error in Tag Manager

I'm trying to use a cookie to set user pageviews per session through GTM. I'm using a custom JavaScript variable:
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for (var i = 0; i < cookieSplit.length; i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1, cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length, cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = oldCookie + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
I keep getting the same Compiler error: "Error at line 12, character 1: Parse error. ')' expected."
I can't seem to figure out what I'm doing wrong, but any help is appreciated.
------ EDIT ------
Via my comment below, this is my current code. Current error is : "Error at line 16, character 40: Parse error. Semi-colon expected"
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount="1"; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
}
You have quoting problems on this line:
document.cookie = "viewCount="1"; path=/";
it should be:
document.cookie = "viewCount=1; path=/";
You don't need to put quotes around the value of a cookie (and if you did, you could either escape them or use single quotes around the whole string).
Alright, I went back to the drawing board and tried approaching the problem another way. At first I was trying to build everything into a single custom JavaScript variable in GTM. That was folly. I decided to approach it as such:
First, I built a custom HTML tag in GTM to read/write the PageView cookie that fired on all pages.
<script>
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
</script>
Then I built a custom Javascript variable that read the cookie and returned it as an integer.
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
var oldCookie = readCookie('viewCount');
var views = parseInt(oldCookie);
return views;
}
Then I simply built my pagievew tag that triggered whenever the pageviews variable was greater than 4 on Window Load to indicate an engaged user.
Thanks #Barmar for the help thinking about the problem. Your questions definitely challenged how I was approaching it.

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

Cookie jquery hide and show div

I wanna use my javascript cookie to let the application see if the user already loggedIn.. i get the value of the cookie in my console.. but whenever i make an statement and wanna hide a div the div doesn't do anything it doesn't show or hide.. can you guys please help me??
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
var user = readCookie('email');
if (!user) {
document.getElementById('loginNav').style.display = 'block';
document.getElementById('username').style.display = 'block';
$("#loginNav").css("display","block");
}else{
$("#loginNav").css("display","block");
console.log( $("#loginNav").css("display","block"));
}
if $('#loginNav').length == 0 then your element has not been loaded yet.
Ensure that this code comes after your jquery link and it is surrounded by a :
$(document).ready(function(){
var user = readCookie('email');
if (!user) {
$('#loginNav, #username').show();
}else{
$("#loginNav, #username").hide();
//did you forget to hide the username?
}
});
Make sure you load all your JS files at the end of your HTML age.
Hi set the "display" property to "none" to hide.... and "block" to show
I would also use "visibility":
if (!user) {
$("#loginNav, #username").css("display","block");
$("#username, #username").css("visibility","visible");
}else{
$("#loginNav, #username").css("display","none");
$("#username, #username").css("visibility","hidden");
}

Categories

Resources