How to disable html button for 24hrs after being clicked - javascript

I'm trying to create a html form button that disable after being clicked and will be enable after 24hrs.
The button should work for each users.
How can I fix that?
<p>
<input type='submit' value='Submit' id='btClickMe'
onclick='save(); this.disabled = true;' />
</p>
<p id="msg"></p>
<script>
function save() {
var msg = document.getElementById('msg');
       msg.innerHTML = 'Data submitted and the button disabled in 24hrs ☺';
}
</script>

store clicked identifier to cookie which expired after 24 hours from first button clicked (using document.cookie)
<input
type="submit"
value="Submit"
id="btClickMe"
/>
<div id="msg">Message Here</div>
const btn = document.getElementById("btClickMe");
let get = getCookie("clicked"); // check cookie after page loaded
if (get) {
btn.disabled = true; // disable the button after page loaded
}
btn.addEventListener("click", function (_event) {
get = getCookie("clicked"); // check cookie exist
if (!get) setCookie("clicked", "true", 1); // set cookie after clicked
btn.disabled = true; // disable the button after button clicked
var msg = document.getElementById("msg");
msg.innerHTML = "Data submitted and the button disabled in 24hrs ☺";
});
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
See Demo

Related

Run script with timeout once per session (but you could reload page and go to another page)

I've got a simple script, that I need to run only once per session of user. But in this session he could refresh page, or go to another page on one site.
My code now looks like this, but if user refresh page (in less then 10 seconds) or go to another page - script will never run :(
var visited = sessionStorage.getItem('visit');
if (visited == null || document.location.href == sessionStorage.getItem('lastPage')) {
setTimeout(function() {
alert('Hello World')
}, 10000
)
sessionStorage.setItem('visit', 1);
};
Working example: https://codepen.io/zavtraleto/pen/GdRpRZ
I think it's something with cookies, maybe
I made it using cookie, so if everyone interested:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
getCookie('user_first_visited') || setCookie('user_first_visited', Date.now());
if (!getCookie('user_popup_triggerred')) {
var loopDetect = setInterval(function(){
var TimePast = (Date.now() - getCookie('user_first_visited')) / 1000;
if( TimePast > 5){
if (localStorage.getItem('surveyOnce') !== 'true') {
(function() {
alert('Hello World!')
}
)();
localStorage.setItem('surveyOnce','true');
};
}
}, 1000);
}

HTML Javascript dynamic changes to a button

Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:
var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
validUser = true;
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("results").innnerHTML = "Welcome " + user +"!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
validUser = false;
}
}
function signin() {
if (document.getElementById("btnSignIn").innerHTML == "Sign out") {
validUser = false;
document.getElementById("btnSignIn").innerHTML = "Sign in";
document.getElementById("btnSignIn").style.backgroundColor = "orange";
document.getElementById("results").innerHTML = "Welcome stranger";
document.getElementById("txtUserName").style.visibility = "visible";
document.getElementById("txtPassword").style.visibility = "visible";
setCookie("txtUserName", null, "txtPassword", null, 365); 
}
else {
var user = document.getElementById("txtUserName").value;
var pwd = document.getElementById("txtPassword").value;
if (user.text === "" && user === null &&
pwd.text === "" && pwd === null) {
validUser = false;
}
else if (user === "john#me.com" && pwd === "snow") {
validUser = true;
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("results").innerHTML = "Welcome "+ user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
if (!myCookie) {
validUser = false;
}
}
return false;
}
}
function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toUTCString();
document.cookie = uname + "=" + uvalue + "; " + expires;
document.cookie = pname + "=" + pvalue + "; " + expires;
return true;
}
else {
return false;
}
}
function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var user = getCookie("username");
if (user !== "") {
return user;
}else {
return false;
}
}
else {
return false;
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
}
<ul class="nav navbar-nav navbar-right">
<li>
<form id="loginform" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" id="txtUserName" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" id="txtPassword" placeholder="Password" class="form-control">
</div>
<button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();" >Sign in</button>
</form>
</li>
</ul>
The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.
You're using outerHTML to set the text of #btnSignIn which replaces the node with just text, since all you provided was text. That removes the #btnSignIn element that you applied the background to. Use innerHTML instead.
You're also missing #results in this demo.
Note, I added return false to an inline onsubmit handler for the form, just for this demo so you can see the state of the button after submitting. You'll probably want to remove that in your actual code.
var validUser;
function init() {
var loginCookie = loginWithCookie();
if (loginCookie === true) {
validUser = true;
document.getElementById("btnSignIn").innerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("results").innnerHTML = "Welcome " + user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
} else {
validUser = false;
}
}
function signin() {
if (document.getElementById("btnSignIn").innerHTML == "Sign out") {
validUser = false;
document.getElementById("btnSignIn").innerHTML = "Sign in";
document.getElementById("btnSignIn").style.backgroundColor = "orange";
document.getElementById("results").innerHTML = "Welcome stranger";
document.getElementById("txtUserName").style.visibility = "visible";
document.getElementById("txtPassword").style.visibility = "visible";
setCookie("txtUserName", null, "txtPassword", null, 365);
} else {
var user = document.getElementById("txtUserName").value;
var pwd = document.getElementById("txtPassword").value;
if (user.text === "" && user === null &&
pwd.text === "" && pwd === null) {
validUser = false;
} else if (user === "john#me.com" && pwd === "snow") {
validUser = true;
document.getElementById("btnSignIn").style.backgroundColor = "pink";
document.getElementById("btnSignIn").innerHTML = "Sign out";
document.getElementById("results").innerHTML = "Welcome " + user + "!";
document.getElementById("txtUserName").style.visibility = "hidden";
document.getElementById("txtPassword").style.visibility = "hidden";
var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
if (!myCookie) {
validUser = false;
}
}
return false;
}
}
function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = uname + "=" + uvalue + "; " + expires;
document.cookie = pname + "=" + pvalue + "; " + expires;
return true;
} else {
return false;
}
}
function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
var user = getCookie("username");
if (user !== "") {
return user;
} else {
return false;
}
} else {
return false;
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
}
<ul class="nav navbar-nav navbar-right">
<li>
<form id="loginform" class="navbar-form navbar-right" onsubmit="return false;">
<div class="form-group">
<input type="text" id="txtUserName" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" id="txtPassword" placeholder="Password" class="form-control">
</div>
<button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();">Sign in</button>
</form>
<div id="results"></div>
</li>
</ul>
You messed up with replacing the text.
Try to use innerHTML, cause you have text inside the tag.
So inside init() it goes like this:
document.getElementById("btnSignIn").outerHTML = "Sign out";
document.getElementById("btnSignIn").style.backgroundColor = "pink";
Yes, as Michael Coker answer, the problem was replacing the whole html element wit the "sign out" text.
I just wanted to add that that example code must be just for testing dinamicaly dom changes, if you wanna practice login/validation DONT ever do that. I mean, the validation logic.

javascript counter with cookies doesn't work

I just tried to make a timer with cookies that makes a button only 3 times clickable (I had to do it with cookies cause it refreshes the page in its process), I made this timer but it doesn't work. Nothing on my page changed at all.
The code I have by //something else happens gets executed by the program.
Timer - (or at least what I thought that would work as a timer) :
mailagain.onclick = function () {
if (typeof getCookie("countIt") !== 'undefined') {
if (checkCookie("countIt") > 3) {
// something happens
} else {
//something else happens
var counter = checkCookie("countIt") + 1;
setCookie("countIt", counter, 1)
}
} else {
setCookie("countIt", 1, 1)
}
};
Coockie functions :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 "";
}
function checkCookie(name) {
var value = getCookie("name");
if (value != "") {
return value;
}
}
Some issues:
When reading the value from the cookie, be aware that it has the string data type. You need to convert it to number before comparing it with another number or adding 1 to it.
The function checkCookie is using the wrong (hard-coded) cookie name, but is even not necessary as a function. You can do all that with getCookie.
Here is a working version:
mailagain.onclick = function () {
// make sure to convert to number (unitary plus), or use 0 when it is not a number:
var counter = (+getCookie("countIt") || 0) + 1;
setCookie("countIt", counter, 1)
if (counter > 3) {
console.log('clicked too many times! (', counter, ')');
} else {
console.log('clicked ' + counter + ' number of times.');
}
};
var value = getCookie("name");
getCookie always return "undefined" because of wrong cookie name. Remove brakets.
function checkCookie(name) {
var value = getCookie(name); //here you go
if (value != "") {
return value;
}
}

Why can't I get a cookie into a variable and then assign a div the result? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I am trying to get the value of a cookie into a global variable in which I can then place into div's by using document.getElementById.
Here is my code - it works prefectly in terms of the fact it remembers the cookie but it just won't do one line in particular which I have clearly outlined with a comment for you.
Here is all my code...
<!DOCTYPE HTML>
<html>
<head>
<script>
var globalVar = "";
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar; /* THIS LINE DON'T WORK WHY NOT! THE ONE BELOW DOES IN THE CHANGE COOKIE FUNCTION DOES! */
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function changeCookie() {
var user = getCookie("username");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
document.getElementById("demo").innerHTML = user; /* THIS WORKS! */
}
checkCookie();
</script>
</head>
<body>
<div id="demo"></div>
<button onclick="changeCookie()">Change username</button>
</body>
</html>
Try calling checkCookie() right after the page has finished loading.
<body onload="checkCookie()">
Another way is to move the script tag to the end of the page, right before the closing tag of body like this:
<html>
<body>
<div id="demo"></div>
<button></button>
<!-- the rest of the page's HTML here -->
<script>
....
.... your script code here
....
....
checkCookie();
</scirpt>
</body>
</html>
You are only assign html into "demo" in the first part of the case statement, you need to add it to the second part, and assign the user variable, not the globalVar. Also place the code at the end of the body as suggested in other answers.
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar;
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
document.getElementById("demo").innerHTML = user;
}
}
}

Contact Form 7 - Set Cookie on submission

So I need a way to grab the values of the fields from a form that uses contact form 7 plugin, using the Additional Settings box on the admin page.
Some way to set a cookie with the field values would be great.
The form:
<label>Please type your question</label>
<fieldset class="question">
[textarea your-message id:questionmessage]
</fieldset>
<label>Name</label>
<fieldset class="name">
[text* your-name id:questionname]
</fieldset>
<label>Email</label>
<fieldset class="email">
[email* your-email id:questionemail]
</fieldset>
<label>[Submit button]</label>
<fieldset class="submit">
[submit "Send"]
</fieldset>
Additional Settings, that works so far:
on_sent_ok: "location.replace('page2');"
I've tried:
on_sent_ok: "setcookie('form-email',1,strtotime('+30 days'),COOKIEPATH, COOKIE_DOMAIN,false, false);setcookie('form-name',1,strtotime('+30 days'),COOKIEPATH, COOKIE_DOMAIN,false, false);location.replace('page2');"
this still sends the email correctly, but does not redirect to page2 (I know this should just set the cookie values to 1)
To Redirect properly contact form 7 please add this code.
on_sent_ok: "location = 'http://example.com/';"
Remember start double commas(") -> single commas(') -> double commas(") otherwise there will be error
I've called in the additional settings box in the admin area.
on_sent_ok: "setCookiesAndRedirect("http://www.redirecthere.com");"
Then in the form area I've added some javascript to handle the form field values/cookie stuff. This probably isn't great but it works.
< script type = "text/javascript" >
window.onload = function() {
var namefield = document.getElementById("formfullname");
var emailfield = document.getElementById("formemail");
var firstnamefield = document.getElementById("formfirstname");
var surnamefield = document.getElementById("formsurname");
var namecookie = getCookie("form-fullname");
var emailcookie = getCookie("form-email");
var firstnamecookie = getCookie("form-firstname");
var surnamecookie = getCookie("form-surname");
if (namecookie != "" && namefield != null) {
namefield.value = namecookie;
}
if (emailcookie != "" && emailfield != null) {
emailfield.value = emailcookie;
}
if (firstnamecookie != "" && firstnamefield != null) {
firstnamefield.value = firstnamecookie;
}
if (surnamecookie != "" && surnamefield != null) {
surnamefield.value = surnamecookie;
}
} //end load function
function setCookiesAndRedirect(url) {
var namefield = document.getElementById("formfullname");
var emailfield = document.getElementById("formemail");
var firstnamefield = document.getElementById("formfirstname");
var surnamefield = document.getElementById("formsurname");
if (namefield != null)
setCookie("form-fullname", namefield.value, 30);
if (emailfield != null)
setCookie("form-email", emailfield.value, 30);
if (firstnamefield != null)
setCookie("form-firstname", firstnamefield.value, 30);
if (surnamefield != null)
setCookie("form-surname", surnamefield.value, 30);
location.replace(url);
} //end setCookiesAndRedirect
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
} //end setCookies
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.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 "";
} </script>
<p>First Name (required)<br />
[text* Firstname id:formfirstname] </p>
<p>Last Name (required)<br />
[text* LastName id:formsurname] </p>
<p>Your Email (required)<br />
[email* your-email id:formemail] </p>
<p>[submit "Download Now"]</p>
Some links that helped me:
cookies in all pages
Cookies in javascript

Categories

Resources