changing the text when the page reloads - javascript

I made a basic form that after you put in an input and submit the cookies show "welcome" + name
I added a second cookie that when you reload the same page the above text disappears and says "welcome back" + name.
I am new to using cookies and cant get the functionality working properly.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<input id="user" type="user" name="user">
<input id = "submit" type="submit" name="submit">
</form>
<h1 id ="greeting" cookie_name ='name'></h1>
<h1 id ="welcome" cookie_name='visited'></h1>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript" src="script/js.cookie.js"></script>
<script type="text/javascript" src="script/script.js"></script>
</body>
</html>
--------------------------------------------------------------------------
<script>
$(document).ready(function(){
if(Cookies.get('name')===undefined){
$('form').submit(function(){
var name = $('input').val()
Cookies.set('name', name)
Cookies.set('visited', 1)
})
}else{
$('form').css('display', 'none')
$('#greeting').append('Welcome ' + Cookies.get('name') + '!')
}
})
if(Cookies.get('visited')===undefined){
$('#greeting').text('Welcome again!')
}else{
$('#greeting').text('Welcome back ' + Cookies.get('name') + '!')
}
<script>

I would actually use sessionStorage.setItem('name', name); to store items and check if items are set like this
if (sessionStorage.getItem("name"))
Check this link
If Cookies is a must this code works for me just fine:
$(document).ready(function () {
if (Cookies.get('name') === undefined) {
Cookies.set('name', 'alexis')
Cookies.set('visited', 1)
} else {
console.log('Name is already set');
}
})
if (Cookies.get('visited') === undefined) {
console.log('welcome for the first time')
} else {
console.log('welcome ' + Cookies.get('name'))
}

Related

Deriving value from textfield to javascript(DOM issue)!

In my palindrome checker, i can't obtain value from the HTML input text-field. I tried various methods including query-selectors. But nonetheless is working. Error in the validator is document.getElement(...) is null.
i need to find whats wrong with my code. Is there any problem in my DOM?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i = document.getElementById('boiler').value;
function check_pal() {
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
I am little sure that my problem is with document model. Because i get correct result when i directly assign the value to the variable. Or else i get "undefined is not a palindrome"
Update your script to following
<script>
function check_pal() {
// move this line inside the function
var i = document.getElementById('boiler').value;
// rev(); // Also removed this un-necessary call
if (i == rev(i)) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
// modify function to take input as argument rather than relying on global variable
function rev(i) {
i = i + "";
return i.split("").reverse().join("");
}
</script>
Reasoning - When you manually assigned the value of i, then it was running correctly. However, when were trying to read it from the getElementById, the element did not existed by then and it throws a JS error (cannot read property 'value' of null), hence, the error (as i was never initialized and remains undefined). Move the retrieving of value inside the function where the latest value can be retrieved and stored in i.
This should solve it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i;
function check_pal() {
i = document.getElementById('boiler').value;
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
Now the i variable gets assigned in the check_pal function and declared in the global space so both functions can access it. I think you should take a close look in scope in javascript.

Trying to make a javascript account system on my page using javascript... but apparently I've overlooked something

My html page seems like ignoring part of the script: when you have an account it doesn't hide the #signup div, and when you don't have one it doesn't hide the #account div: here is the JavaScript code:
if(localStorage.hasAnAccount){
$('#signup').hide();
$('#AccountName').html(localStorage.accountName)
}else{
$('#account').hide();
}
function createNewAccount(){
localStorage.accountName=$('#newAccountName').html();
localStorage.accountPassword=$('newAccountPassword').html();
if(typeof localStorage.accountName=='string'&& typeof localStorage.accountPassword=='string'){
alert('congrats! Your account has been made!');
localStorage.hasAnAccount=true;
}else{
alert('check that your name and password are alphanumeric strings');
}
}
And here is the HTML code:
<html>
<head>
<title>Account | Cicada3301's Website</title>
<link rel='stylesheet' type='text/css' href='http://www.copot.eu/matei/assets/stylesheet.css'>
<link rel='stylesheet' href='http://www.copot.eu/matei/assets/jquery-ui-stylesheet.css'>
<script type="text/javascript" src="http://www.copot.eu/matei/assets/jquery-1.10.2.min.js"></script>
<script src="http://www.copot.eu/matei/assets/jquery-ui.js"></script>
<script type="text/javascript" src="http://www.copot.eu/matei/assets/scripts.js"></script>
<script type='text/javascript' src='http://www.copot.eu/matei/account/account-scripts.js'></script>
<link rel='shortcut icon' type='image/x-icon' href='http://www.copot.eu/matei/assets/me.jpg'>
</head>
<body>
<div id='account'>
<div id='AccountName'></div>
</div>
<div id='signup'>
<p><input type='text' id='newAccountName'> Insert your account name</p>
<p><input type='text' id='newAccountPassword'> Insert your account password</p>
<p><input type='button' onclick='createNewAccount()' value='Create Account'></p>
</div>
</body>
</html>
What I think happened is that I didn't set the localStorage Object to be anything at first... but I have no idea how localStorage works other than it is an Object and in all samples of this Object I never found anyone declare the variable
If I've overlooked something else here is the link to the page: http://www.copot.eu/matei/account
|UPDATE|
after what you told me this should be the outcome, but still doesn't work:
$(document).ready(function(){
if (localStorage.hasAnAccount) {
$('#signup').hide();
$('#AccountName').html(localStorage.accountName)
} else {
$('#account').hide();
}
$('#createNewAccount').click(
function () {
if (typeof localStorage.accountName == 'string' && typeof localStorage.accountPassword == 'string') {
localStorage.accountName = $('#newAccountName').val();
localStorage.accountPassword = $('newAccountPassword').val();
alert('congrats! Your account has been made!');
localStorage.hasAnAccount = true;
} else {
alert('check that your name and password are alphanumeric strings');
}
});
})
I found it:
first, i suggest you to avoid inlined javascript events.
Replace this line : <input type='button' id="createNewAccount" value='Create Account' />
Your 'bug' was with the data-type from the input:text fields. Replace them for .val() instead of .html()
if (localStorage.hasAnAccount) {
$('#signup').hide();
$('#AccountName').html(localStorage.accountName)
} else {
$('#account').hide();
}
/* run your fonctionnality upon the id of your button */
$('#createNewAccount').click(
function () {
/* replace .html() by .val() */
localStorage.accountName = $('#newAccountName').val();
/* replace .html() by .val() */
localStorage.accountPassword = $('newAccountPassword').val();
/* this next testing will not validate for alphanumeric */
if (typeof localStorage.accountName == 'string' && typeof localStorage.accountPassword == 'string') {
alert('congrats! Your account has been made!');
localStorage.hasAnAccount = true;
} else {
alert('check that your name and password are alphanumeric strings');
}
});
jsfiddled here
and a version with a 'clearStorage' button to play.
Just to mention:
you have to re-run the script on jsFiddle to see it applied.
you have javascript errors on your page (ReferenceError: barHeight is not defined
SourceĀ : http://www.copot.eu/matei/assets/scripts.js LineĀ : 33) witch blocks the rest of the scripting.

direct user to php page with javascript + an id

I am very new to javascript - mainly only used it to go back a page or go to a link ..
I got it working on the example page, now I'm trying to get it to work on my website ... However nothing occurs when the link is pressed...
The files exist in their linked locations. The script is copied from the example.
HEADER:
<script type="text/javascript" src="js/jquery-impromptu.min.js"></script>
<link rel="stylesheet" media="all" type="text/css" href="css/jquery-impromptu.css" />
<script type="text/javascript">
function removeUser(id){
var txt = 'Are you sure you want to remove this user?<input type="hidden" id="userid" name="userid" value="'+ id +'" />';
$.prompt(txt,{
buttons:{Delete:true, Cancel:false},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
window.location = "deletemember.php?id=" + id;
}
else{}
}
});
}
</script>
LINK :
<a href='javascript:;' onclick='removeUser(544666);'>Delete</a>
Check this demo: https://github.com/trentrichardson/jQuery-Impromptu/blob/master/demos/user_manager.html
What you should do is make a function. This function is called when a user does something, but it should contain an ID. For example:
Edit
So, as you can see you will call the function 'editUser(4)' where 4 is the ID.
Back to JS
function editUser(id){
}
In this function you add your part, and you end up with this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="../jquery-impromptu.js"></script>
<script type="text/javascript">
function removeUser(id){
var user = $('#userid'+id)
var fname = user.find('.fname').text();
var lname = user.find('.lname').text();
var txt = 'Are you sure you want to remove this user with id: '+id+'?';
$.prompt(txt,{
buttons:{Change:true, Cancel:false},
submit: function(e,v,m,f){
var flag = true;
if (v) {
window.location = "deletemember.php?id=" + id;
}
return flag;
}
});
}
</script>
<a href='javascript:;' onclick='removeUser(544666);'>Delete</a>
Now the ID is useable for your window.location.
Use window.location.href or window.location.replace:
<script type="text/javascript">
function removeUser(id) {
var txt = 'Are you sure you want to remove this user?<input type="hidden" id="userid" name="userid" value="' + id + '" />';
$.prompt(txt, {
buttons: {
Delete: true,
Cancel: false
},
close: function (e, v, m, f) {
if (v) {
var uid = f.userid;
//window.location.href = "deletemember.php?id=" + uid;
window.location.replace("deletemember.php?id=" + uid);
} else {}
}
});
}
</script>
You can read about the difference here.

removing contents on jquery

Hello im a little bit new on doing javascript and jquery please kinda help me on my problem. i would really appreciate it. Thank you!
On page 7-8 how can I remove the "disabled" on the "new game" button
Using jquery?
Here's the index.html:
<!DOCTYPE>
<html>
<head>
<link href="assets/css/blackjack.css" type="text/css" media="screen" rel="stylesheet">
<script src="assets/js/Modernizr.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/Mustache.js"></script>
<script src="assets/js/blackjack.js"></script>
</head>
<body>
<div class="wrapper">
<img src="assets/images/rocket-u-logo-large.png">
<h1>Blackjack</h1>
<p>Hi, thanks for stopping by our blackjack table. Pull up a chair and let's play...</p>
<div id="card-table">
<h2>Dealer</h2>
<div id="dealer-hand"></div>
<div id="status"></div>
<div id="player-hand"></div>
<h2>Player</h2>
<div id="player-options">
<button class="bj" id="new-game" disabled>New Game</button>
<button class="bj" id="hit">Hit</button>
<button class="bj" id="stand">Stand</button>
</div>
</div>
</div>
</body>
</html>
and Here's the js:
$('#bj').click(function () {
$('#hit').show();
$('#stand').show();
});
function initGame() {
var initErrors = [];
var errorMessage;
// Test if browser supports local storage
if (Modernizr.localstorage) {
// console.log("Local storage is supported.");
} else {
var errorStatus = "Local storage is not available"
// console.log(errorStatus);
initErrors.push(errorStatus);
}
// Test if browser supports mustache.js
var mustacheScript = $('script[src*="js/Mustache.js"]').length;
if (mustacheScript != 0) {
// console.log("Mustache loaded!");
} else {
var errorStatus2 = "Mustache not loaded."
// console.log(errorStatus2);
initErrors.push(errorStatus2);
}
function displayErrorMessage() {
// Test if initErrors array has any errors
if (initErrors.length != 0) {
if (errorStatus2 === undefined) {
errorStatus2 = "";
} else if (errorStatus === undefined) {
errorStatus = "";
}
var errorMessage = "Houston, we have a problem (" + errorStatus + ', ' + errorStatus2 + ").";
// console.log(errorMessage);
$('#status').append("<p>" + errorMessage + "</p>");
} else {
var successMessage = "Ready to play? Click 'New Game' to start...";
$('#status').append("<p>" + successMessage + "</p>");
// console.log(successMessage);
}
}
displayErrorMessage();
//Test 'boolean' return values
if (initErrors.length != 0) {
return false;
$('#new_game').attr("disabled", "disabled");
} else {
return true;
$('#new_game').removeAttr("disabled");
}
}
console.log(initGame());
$(document).ready(function () {
initGame();
});
You wrote the code yourself. but it was below return statement which will make it in accesible.
bring the return statement below
$('#new_game').removeAttr("disabled");
It should work.
You can try this:
$('#new_game').prop('disabled',false);
You can use anyone of listed below
$('#new_game').attr("disabled", false);
OR
$("#new_game").removeAttr("disabled");
OR
$("#new_game").prop("disabled",false);
$('#new-game').removeAttr('disabled');
Looks like your JS code has an error: in HTML <button class="bj" id="new-game", but in JS $('#new_game').removeAttr("disabled");. You use underscore instead of '-' in id.

JavaScript display new page when submit HTML form

Suppose I have 2 html files: form.html and confirm.html
form.html just have a text field and a submit button, when you hit submit it will display what you just typed in text field.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script type="text/javascript">
function display(){
document.write("You entered: " + document.myform.data.value);
}
</script>
</HEAD>
<BODY>
<center>
<form name="myform">
<input type="text" name="data">
<input type="submit" value="Submit" onClick="display()">
</form>
</BODY>
</HTML>
Now I want that when hit submit button it will display entered value in confirm.html. What should I do? I mean what should be in confirm.html and how data from form.html be used in other location, do I need create a separate JavaScript file to store JS function so I can use it in both 2 html files. I am kind of new to all kind of stuff.
Note: No PHP or server side language or anything super here, just 2 html files in my Desktop and I want to test using FireFox.
Thank you!
You can try using localStorage or cookies. Check one of the 2 solutions found below...
1 - If you have HTML5, you can store the content of you input into the localStorage.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
2 - Also, as #apprentice mentioned, you can also use cookies with HTML standards.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Function for storing to cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into a cookie
setCookie("mytext", mytext, 300);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Function for retrieveing value from a cookie
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into a cookie
var mytext = getCookie("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
What you could do is submit the form using a get method (method="get"), and send it to your confirm.html page (action="./confirm.html").
Then, you could use jQuery to retrieve the values from the URL from your confirm.html page.
This website provides a method to do that: http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html .
Then, all you have to do is call your display() method.
Seams like a fit for persist.js, which will let you save and load data in the user's browser. After including its javascript file, you can save data like this:
var store = new Persist.Store('My Application');
store.set('some_key', 'this is a bunch of persistent data');
And you can later retrieve the saved data in another html page like the following:
var store = new Persist.Store('My Application');
val = store.get('some_key');
You could also, instead of changing the page, change the content of the page. Upon submission just change the page using the innerHtml variable.

Categories