Cannot understand why I can't read java cookies by name - javascript

okay, I have been pulling my hair out for hours with this one and now that I'm completely bald I'm throwing in the towel and seeing if anyone can point to the (I'm sure very simple) mistake that is turning my code into useless junk.
I have two pages, the first one the user enters 3 inputs and they are saved as cookies:
<script type="text/javascript">
function CC()
{
var V1Box = document.getElementById("V1");
var V2Box = document.getElementById("V2");
var V3Box = document.getElementById("V3");
var V1 = V1Box.value;
var V2 = V2Box.value;
var V3 = V3Box.value;
document.cookie = "V1 = " + V1 + "; path=/";
document.cookie = "V2 = " + V2 + "; path=/";
document.cookie = "V3 = " + V3 + "; path=/";
window.location = "pg2.html";
}
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Generator" content="Serif WebPlus X5">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
<title>db2</title>
<style type="text/css">
body {margin: 0px; padding: 0px;}
.Artistic-Body-C
{
font-family:"Verdana", sans-serif; font-size:27.0px; line-height:1.19em;
}
</style>
<link rel="stylesheet" href="wpscripts/wpstyles.css" type="text/css">
</head>
<body text="#000000" style="background-color:#ffffff; text-align:center; height:900px;">
<div style="background-color:transparent;text-align:left;margin-left:auto;margin
right:auto;position:relative;width:375px;height:900px;">
<form id="form_1" action="" method="post" target="_self" style="margin:0px;">
<input type="button" style="position:absolute; left:271px; top:12px; width:81px;
height:22px;" value="Submit" onClick="CC()">
<input type="text" id="V1" name="V1" value="" style="position:absolute; left:23px;
top:12px; width:227px;">
<input type="text" id="V2" name="V2" value="" style="position:absolute; left:23px;
top:46px; width:227px;">
<input type="text" id="V3" name="V3" value="" style="position:absolute; left:23px;
top:80px; width:227px;">
</form>
</div>
</body>
</html>
The second page is supposed to get the cookies previously set and isolate there values:
<script type="text/javascript">
window.onload = function getCookie(){
var allcookies = document.cookie;
cookiearray = allcookies.split(';');
for(var i=0; i < cookiearray.length; i++){
var name = cookiearray[i].split('=')[0];
var value = cookiearray[i].split('=')[1];
if(name == 'V1'){var V1 = value;}
if(name == 'V2'){var V2 = value;}
if(name == 'V3'){var V3 = value;}
}
document.getElementById("V1").innerHTML += V2;
document.getElementById("V2").innerHTML += V1;
document.getElementById("V3").innerHTML += V3;
}
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Generator" content="Serif WebPlus X5">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
<title>db2</title>
<style type="text/css">
body {margin: 0px; padding: 0px;}
.Artistic-Body-C
{
font-family:"Verdana", sans-serif; font-size:27.0px; line-height:1.19em;
}
</style>
<link rel="stylesheet" href="wpscripts/wpstyles.css" type="text/css">
</head>
<body text="#000000" style="background-color:#ffffff; text-align:center; height:900px;">
<div style="background-color:transparent;text-align:left;margin-left:auto;margin
right:auto;position:relative;width:375px;height:900px;">
<div style="position:absolute;left:23px;top:12px;">
<div class="Wp-Artistic-Body-P">
<span class="Artistic-Body-C" id="V1">V1: </span></br>
<span class="Artistic-Body-C" id="V2">V2: </span></br>
<span class="Artistic-Body-C" id="V3">V3: </span></br></div>
</div>
</div>
</body>
</html>
The issue I have is that the code does not recognize any of the names in these if statements -- even if I echo the name and value; it will echo "V3" and the corresponding value, but the V3 variable is never set and will echo as "undefined". I am losing my mind trying to figure out how it can have the name set as "V3" but then not recognize "if(name == 'V3'){var V3 = value)" and keep var V3 undefined. I have even tested "if(name != 'V3'){var V3 = value)" and, even when echoing the name and getting "V3" it will interpret name not equaling V3 in the if statement and actually set the appropriate V3 variable value. I don't understand how it can name everything properly, retrieve everything properly, and then not recognize the name in an if statement to set the variable properly -- doesn't matter if I'm calling V1 or V2 or V3; it just doesn't see those names inside of the if statements.
I'm sure this is something stupid in my syntax or there's a typo or something, but after three hours of trying to fix it myself I'm clearly blind to it. I recognize that there are other, simpler ways to manipulate user inputs, but my project as a whole requires that I use cookies and that I am able to retrieve them by name on different pages; if you have any suggestions for how I can accomplish this criteria in a better way I would be very much appreciative, however just getting my current code to work properly would be a big help and my scalp (which as I continue to claw for any remaining strands of hair has begun bleeding profusely) will very much thank you for it.

Look at where V1, V2, V3 are declared!
if(name == 'V1'){var V1 = value;} <-- what happens if not true
if(name == 'V2'){var V2 = value;} <-- what happens if not true
if(name == 'V3'){var V3 = value;} <-- what happens if not true
They will not be defined.
You need to have
var v1 = "";
var v2 = "";
var v3 = "";
declared and drop the var inside the ifs.
JSLint/JSHint would have pointed out this error.
Third issue is innerHTML can not have +=
document.getElementById("V1").innerHTML = document.getElementById("V1").innerHTML + V1;
Other issue is whitespace in the names. Cookies have a space after the ; which you do not account for in the name.

<script type="text/javascript">
function getCookie(){
var allcookies = document.cookie;
cookiearray = allcookies.split(';');
for(var i=0; i < cookiearray.length; i++){
var name = cookiearray[i].split('=')[0];
var value = cookiearray[i].split('=')[1];
if(name == 'V1'){var V1 = value;}
if(name == 'V2'){var V2 = value;}
if(name == 'V3'){var V3 = value;}
}
document.getElementById("V1").innerHTML += V2;
document.getElementById("V2").innerHTML += V1;
document.getElementById("V3").innerHTML += V3;
}
window.onload = getCookie;
</script>
I don't believe the getCookie function was ever run.

Related

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

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.

Get the image from Google Feeds API

I know this is likely very easy however I have been bashing my head for little over an hour and I am stuck.
I am trying to use Google Feed API to show a list of recent houses, It works just fine until it comes to pulling the image. I am struggling to get it to pull the image. I am sure there is a way because the slideshow script that google released can get the images...
Here's my code taken from a basic example I am absolutely clueless as to where to go to even try and figure out how to retrieve the image.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Google Feed Loader Example #1</title>
<script type="text/javascript" src="http://www.google.com/jsapi?key=#"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.trulia.com/rss2/San_Francisco,CA/3p_baths/3p_beds/800000-2000000_price/date;d_sort/");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var bmfx = result.feed.entries[i].mediaGroups[0].contents[0].url;
var li = document.createElement("li");
li.innerHTML = '<h3>' + entry.title + ' <cite>by ' + entry.mediaGroup + '</cite></h3>';
li.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(li);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Ooops It Failed';
}
});
}
</script>
</head>
<body>
<h1>Google Feed Loader Example</h1>
<ul id="headlines"></ul>
</body>
</html>
According to your case, you should use:
var bmfx = entry.mediaGroups[0].contents[0].thumbnails[0].url;

Why one requires getElementById and the other doesn't

Why does this work
app.prints(address,list.options[list.selectedIndex].value);
but this doesn't?
app.prints(status,macAddress);
JavaScript
var hey = 5;
var app = {
createList: function () {
for (var i = 0; i < 5; i++) {
list.options[i] = new Option(hey + i, "mac" + i);
}
app.prints(address, list.options[list.selectedIndex].value);
},
prints: function (location, message) {
location.innerHTML = message;
},
manageConnection: function () {
var macAddress = list.options[list.selectedIndex].value;
app.prints(status, macAddress);
}
}
HTML
<!DOCTYPE html>
<!-- Don't panic! All this
code looks intimidating but eventually it will make sense. -->
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="ECMA.js"></script>
<title>My LCD code</title>
</head>
<body onload="app.initialize();">
<p>Welcome to the LCD software</p>
<select id="list" onchange="app.prints
(address,list.options[list.selectedIndex].value);"></select>
<div id="address"></div>
<button id="connect" onclick="app.manageConnection();">Connect</button>
<div id="status">hi</div>
</body>
</html>
The difference is that a global status variable has already been defined by the browser to represent the text in the status bar. And, browsers don't allow a reference to the element to replace it.
To avoid the naming conflict, you can rename the element.
But, you really shouldn't depend on automatic globals for ids. Not all browsers implement the feature, and some only in certain modes.
var list = document.getElementById('list');
var address = document.getElementById('address');
app.prints(address, list.options[list.selectedIndex].value);

Javascript for loop for text substitution

I try to use for loop as the substitution of list all
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
relaced by
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('editBox'+i));
}
}
but it seems it doesn't work for me. How to correct it?
Below is fully working code without "for loop":
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> New Document </title>
<meta name="title" content="" />
<meta name="author" content="0xs.cn" />
<meta name="subject" content="" />
<meta name="language" content="zh-cn" />
<meta name="keywords" content="" />
<style type="text/css" >
/* default css rule */
body { font: 12px "Verdana"; }
</style>
<script type="text/javascript" >
// shortcut
function $(s){
return typeof s == 'object'?s:document.getElementById(s);
}
var dEdit = function(el){
var me = this;
this.save = function (txt){
el.innerHTML = txt;
};
this.edit = function (e){
var e = e || event;
var target = e.target || e.srcElement;
if(target.tagName.toLowerCase() == 'input'){
return;
}
var ipt = document.createElement('input');
ipt.value = target.innerHTML;
ipt.onkeydown = function(){
if((arguments[0]||event).keyCode==13){
me.save(this.value);
}
};
ipt.onblur = function(){
me.save(this.value);
};
target.innerHTML = '';
target.appendChild(ipt);
ipt.focus();
};
el.onclick = this.edit;
};
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
window.onload = init;
</script>
</head>
<body>
<span id="editBox">This is sample text.</span> <br/><br/>
<span id="editBox2">This is sample text 222.</span> <br/><br/>
<span id="editBox3">This is sample text 333.</span>
</body>
</html>
Change the ids on your span tags to "editBox0", "editBox1" and "editBox2". Also, you posted this exact same question not 20-30 minutes ago and someone gave you the correct answer then too.
You need to add # prefix for ID selectors. Change your code to:
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
Among other issues like what happens when you call dEdit(...) on an empty jQuery object...
You need a # prefix to select an ID:
$('#editBox2')
Your loop goes from 0 to 1000 and editBoxN is not a valid ID selector, so you end with
new dEdit($('editBox0'));
new dEdit($('editBox1'));
new dEdit($('editBox2'));
...
change first editBox ID, the loop variable and add a hash to the jquery selector to match the IDs
function init(){
for(var i = 1; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}
The problem is the init is throwing an expection on the first value, since 'editBox0' does not exist. To fix this you can wrap each loop iteration in a try/catch.
e.g.
function init(){
for(var i = 0; i < 1000; i++){
try {
new dEdit($('editBox'+i));
} catch (e) {}
}
}
This way, if an id is undefined, the script still runs. Also, you should change <span id="editBox"> for <span id="editBox0"> or <span id="editBox1"> if you intend to have it assigned on the loop.

Categories