Ghost element in javascript - javascript

So I've been designing a remember me button using cookies, and I made two functions to do so:
function checkInfo() {
var blah = $("#remem");
alert(blah.id);
var login = $("#nameInput").val();
var pw = $("#pwInput").val();
if (blah.checked) setCookie(login, pw, 5);
if (localStorage[login] == pw) {
$("#loginscreen").css("display", "none");
$("#ques0").css("display", "block");
} else alert("Your info doesn't match, sorry :(");
}
function setCookie(name, value, daysToLive) {
alert(name);
var text = name + "=" + encodeURIComponent(value);
text = text + ";max-age=" + (daysToLive*60*60*24);
document.cookie = text;
alert(text);
}
For some reason blah can't find the #remem element when run in this form:
<form id = "loginscreen">
<p class = "input" style = "display: block; margin: 0 0 30px 0">Now, log in :)</p>
<p class = "input">Login:</p><input id = "nameInput" type = "text" name = "fName" />
<p class = "input">Password:</p><input id = "pwInput" type = "text" name = "password" />
<input type = "button" value = "Submit" onclick = "checkInfo();" />
<p class = "input">Remember me</p><input id = "remem" type = "checkbox" name = "remember" />
</form>
It's weird, because it finds #nameinput and #pwInput right above it. I also just started javascript like a week ago. help!

blah is a jQuery object, not a plain DOM element, and as such, it does not have id or checked properties. Use prop to access them, e.g., blah.prop('id') and blah.prop('checked'). Alternatively, you can get the underlying DOM element from the jQuery object with blah.get(0).

You are not setting localstorage and you accessing it, so it will create error.
You can create two functions like createCookie and readCookie` like that,
function readCookie(name) {
if(typeof(Storage)!=="undefined"){
// window.localStorage is available!
return localStorage.getItem(name);
} else {
createCookie(name,"",-1);
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;
}
}
//Add cookies//
function createCookie(name,value,days) {
if(typeof(Storage)!=="undefined"){
// window.localStorage is available!
localStorage.setItem(name, value);
} else {
// no native support for HTML5 storage :(
// maybe try dojox.storage or a third-party solution
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires=0";//+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
}
// Use this function in your function like,
function checkInfo() {
var blah = $("#remem");
alert(blah.id);
var login = $("#nameInput").val();
var pw = $("#pwInput").val();
if (blah.checked) createCookie(login, pw, 5);
if (readCookie(login) == pw) {
$("#loginscreen").css("display", "none");
$("#ques0").css("display", "block");
} else alert("Your info doesn't match, sorry :(");
}

Related

I tried to make a name stored into a cookie, but it stopped working

I was trying to make a page where we can chat and it will store its user's name to a cookie on the page. I tried it for a couple times, it worked. Then suddenly the cookie part doesn't work anymore. I am hosting the code on replit. What is the problem?
This is my code:
<!DOCTYPE html>
<html>
<head>
<script>
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 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 checkCookie() {
user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
let user = getCookie("name");
document.getElementById("name").value = user;
}
else {
checkCookie()
}
}
function checkname() {
let user = getCookie("name");
if (user == "" && user == null) {
checkCookie()
}
else{
document.getElementById("welcome").innerHTML = "Welcome Back " + user;
document.getElementById("name").value = user;
}
}
</script>
</head>
<body onload=checkname()></body>
<p id="welcome"></p>
<form action="https://online-chat-2.red78massive157.repl.co" method="post">
Name: <br><input name="name" type="text" id="name" readonly/><br>
Message: <br><input name="message" type="text" style='height:100px; width:1000px' required/><br>
<input value="Send" type="submit"/>
</form>
<button onclick=checkCookie()>Change name</button>
<br><br>
<iframe src="https://online-chat-2.red78massive157.repl.co/chat" style='height:1000px; width:500px'/>
</html>
I am not really sure whats not working for you but I found that checkCookie function has an issue. You are trying to use variable user before initialization.
Rewrite code as
function checkCookie() {
const user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
document.getElementById("name").value = getCookie("name");
}
else {
checkCookie()
}
}

How can I set a variable to a text input and then make it appear on screen

I am making a text based game for school and I am stuck with trying to set a variable as an text input. What I would like to happen is the player type start into the input and it do what is inside of the if statement. However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start".
//js
var name = "";
var beginBeenTo = false;
if (beginBeenTo == false) {
if (input == "START") {
beginBeenTo = true;
page = page + 1;
healthPoints = 25;
soundEveningBreeze.play();
$("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
$("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);
if (input != "" || namingBeenTo == false) {
name = input;
}
}
}
document.getElementById("print_name").innerHTML = name;
Quite simply, watch for some event (keyup in my case), check if the input value is START, if so ask for a username.
var started = false;
var username = '';
$('input').on('keyup', function(){
var tmpValue = $(this).val();
if(started){
username = tmpValue
}
if(tmpValue === 'START') {
started = true;
$(this).val('')
$(this).attr('placeholder','Username')
}
$('#username').text(username)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="username"></span>
<br>
<input type="text" placeholder="Type START to play">
it could be done with use of function like this :
var name = "";
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;
you were missing one of #(hashtag)
And this code would work
Thanks & Cheers

save option in input select after refresh

I've made a function with javascript that can add an option in input select if it not exist by selecting option other but after refresh the option added disappear I want to keep it after refresh but i don't know how to do it please if anyone can help i'll be very grateful
It's not possible without having any backend that can save your option somewhere and populate your select option list latter from that saved options.
For this you have to populate your select box option from a array or something similar. Then when you add option to your select box using jquery you must update array. After refresh you will get new option appear properly.
You can also use localStorage. When you populate an input, save it. And when you are going to draw the input, check if localStorage have the data, and prepopulate it
You can use a cookie to save the value then re-populate on refresh
Angular
angular.module('ddlChoiceExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var ddlChoice= $cookies.get('ddlChoice');
// Setting a cookie
$cookies.put('ddlChoice', 'Option1');
}]);
Or in JS
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 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;
}
here is my function to add option select:
<script type="text/JavaScript"> function AjoutOptionAuSelect(this_select) {
if (this_select.value == "autreVille")
{
var saisie;
var pass = false;
do
{
if (pass) alert("La valeur est incorrecte. Elle ne doit comporter que des lettres.");
saisie = prompt("Entrer la nouvelle valeur :");
if (saisie == null) return false;
pass = true;
}
while (saisie.match(/[^a-z^éèàç]/i) && saisie != "")
this_select.options[this_select.length] = new Option(saisie, saisie, true, true);
for (var i=0; i < this_select.options.length; i++)
{
if (this_select.options[i].value == saisie)
{
this_select.options[i].selected = true;
}
}
} }</script>
and input select:
<?= $this->Form->input('ville',
array(
'label'=> false,
'options' => array('Casablanca'=>'Casablanca','Rabat'=>'Rabat', 'Fès'=>'Fès','Tanger'=>'Tanger','Marrakech'=>'Marrakech',
'Essaouira'=>'Essaouira','autreVille'=> 'autreVille' ),
'class' => 'form-control ',
'id'=>'ville',
'onChange'=> "AjoutOptionAuSelect(this);"
)
); ?>

Javascript cookie not saving when user input reaches a certain size

I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
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 GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle

Storing the clicked value in radio buttonswith cookies [duplicate]

This question already has answers here:
Keep the selected option saved within js
(4 answers)
Closed 8 years ago.
Hey guys am new to js actually..I have two radio buttons and a save button..The code i have done
<input id="male" type="radio" name="sex" id="male" value="male">Male
<input id="female" type="radio" name="sex" id="female" value="female">Female
<button id="buttons">Save me </button>
<script>
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;
}
var c = document.getElementById('buttons');
c.onclick = function() {
var c = document.getElementById('male');
var m = document.getElementById('female');
if(c.checked == 'true') {
setCookie('samplecookie', c.value, 30 );
} else if(n.checked == 'true') {
setCookie('anothersamplecookie', n.value, 30);
}
}
</script>
What should i need to do.
Suppose i clicked on the female radio button and click the save button the value needs to be stored and the value will remain be checked even the page is refreshed..The above code didnt works for me ..The radio button gets unchecked when the page is refreshed..
I have asked a similar qus here.But it didnt helped me ..I have heard this can be done with localstorage too..But i dont reall know how to.
Hope you guys would help me with the right code and will be really appreciated..
You need to set AND get the cookie.
FIDDLE
function setCookie(name, value, days) { // from http://www.quirksmode.org/js/cookies.html
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
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;
}
window.onload = function () {
var gender = getCookie('samplecookie');
if (gender) {
if (gender=="male") document.getElementById('male').click(); // or .checked=true;
else if (gender=="female") document.getElementById('female').click();
}
document.getElementById('buttons').onclick = function () {
var m = document.getElementById('male');
var f = document.getElementById('female');
if (m.checked) {
setCookie('samplecookie', m.value, 30);
} else if (f.checked) {
setCookie('samplecookie', f.value, 30);
}
}
}
I don't know if this is something you'd want. But a thing that comes up to mind is the HTML5 Web Storage functionality.With that feature you can store data on the computer of the user.
So whenever a user changes an input field you can create a javascript call that stores the value into the localstorage:
localStorage.setItem(“inputName”, “value”);
Then when you load the page, you see if any of these values are stored and then fill them in.

Categories