var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += ' > ';
}
}
document.write(trailHTML);
trail is an arraylist of valid pages, like so:
['some name', 'another name','yet another name','name']
getURL just takes that name and adds a '-' in between words, which is the page name. This has been tested and works. (for example, getURL('some name') returns 'some-name')
The problem is, when run in IE9 (untested in other browsers), when I write trailHTML to the page, I only get the last element in the array. Why is this?
Let me know if you need any clarification...
function getURL(txt){
return txt.replace(/ /g,"-");
}
var trail = ['some name', 'another name','yet another name','name'];
///////////////////////////////////////////////////
var pre = '<a href="someDirectoryPath/'; // changed
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML += pre + getURL(trail[i]) + mid + trail[i] + post;
if(i<trail.length-1)trailHTML+=" > " // changed
}
document.write(trailHTML);
You have a syntax error in your for-loop: The open "{" on the if does not have a matching "}".
I ran a small sample in IE9 and got all items in the array, not just the last item as you report. Here's what I ran:
<script type="text/javascript">
function getURL(s){
return s.replace(" ", "-");
}
var trail = ['some name', 'another name','yet another name','name'];
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += " > ";
}
}
trailHTML = trailHTML + getURL(trail[0]);
document.write(trailHTML);
</script>
The output looked like this:
some name > another name > yet another name > namesome-name
Most likely your issue is caused by the syntax error, or in how the array is built/passed into your function.
Related
I have written this code which is supposed to print the information from the xml file into a list for each faculty member. I want to eventually place all of these into a table, but need to know how to print them to the screen first.
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseXML);
var faculty = this.responseXML.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++) {
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += "<li><a href = " + name + title + "</a></li>";
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
}
};
xhttp.open("GET", "faculty.xml", true);
xhttp.send();
}
window.onload = init;
Here is the XML file:
<facultyInfo>
<faculty>
<name>Prof A</name>
<title>Professor and Program Coordinator</title>
<office>CI 555</office>
<phone>(999-999-9999</phone>
<email>ProfA#school.edu</email>
</faculty>
<faculty>
<name>Prof B</name>
<title>Visiting Professor</title>
<office>CI 333</office>
<phone>999-999-9999</phone>
<email>ProfB#school.edu</email>
</faculty>
</facultyInfo>
This line:
strOut += "<li><a href = " + name + title + "</a></li>";
... is both malformed and probably not what you intended. Between the missing quotes for the href attribute, missing the ">" to close off the <a> start, and not putting any text in between <a></a>, this results in a link tag where the link destination (href) is set, but the actual text to show to the user is not set. I don't see any links in your XML (maybe that is for the future), so for now you probably want something like this:
strOut += '<li>' + name + ', ' + title + '</li>';
Here is a quick demo with your XML input:
<div id="output"></div>
<script>
var xmlString = '<facultyInfo> <faculty> <name>Prof A</name> <title>Professor and Program Coordinator</title> <office>CI 555</office> <phone>(999-999-9999</phone> <email>ProfA#school.edu</email> </faculty> <faculty> <name>Prof B</name> <title>Visiting Professor</title> <office>CI 333</office> <phone>999-999-9999</phone> <email>ProfB#school.edu</email> </faculty> </facultyInfo>';
var xmlDoc = (new DOMParser()).parseFromString(xmlString,'text/xml');
// var faculty = this.responseXML.getElementsByTagName("faculty");
var faculty = xmlDoc.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++){
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += '<li>' + name + ', ' + title + '</li>';
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
</script>
I was given this task with some existing code to change the string color of each of three selector.value(s) that is output onto an input element to three different colors. The code boils the three selectors into a single output variable. Without destroying the code, I cannot figure out how to select each individual variables prior to condensing them.
If I could use the fontcolor() method, my life would be great but it's 2018 and I can't. Is there any way you can think of to solve this issue?To clarify, I need to alter the colors of the strings that belong to output(red), select1.value(blue) and select2.value(black.
Most of the action for this is happening in the parseOutput() function but I'm just stuck and don't think it's possible without rewriting the entire program.
function updateSelector(result){
var options = result.options;
var elementId = "select" + result.element;
var logger = document.getElementById('logger');
var selector = document.getElementById(elementId);
//logger.innerHTML = JSON.stringify(elementId);
selector.innerHTML = options;
selector.disabled = false;
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
plate();
function resetAll(){
for (var i = 0;i<3;i++){
var selector = document.getElementById('select' + i);
selector.disabled = true;
selector.innerHTML = "";
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
}
function finalSelection(){
var output = document.getElementById('out');
//output.focus();
output.select();
}
function plate(){
var plate = document.getElementById('plate');
plate.innerHTML = atob('Q3JhZnRlZCBieTogWmFjaGFyeSBTdGFjaG93aWFr');
}
//Adds the location as initial output, followed by divider, application, and issue if select1 is selected
//else statement added so if select0 is [Costco Website Name], to ommit the " - "
function parseOutput(){
var output = "";
if (select1.value.length > 0 && select0.value !== "[Costco Website Name]"){
output = output + ' - ' + select1.value + ' // ' + select2.value;
} else{
output = output + select1.value + ' // ' + select2.value;
}
out.value=output.trim();
}
And this is the Div that displays the output:
<div class="wide"><p><input class="wide" type="readonly" id="out" onfocus="this.select();"></p></div>
A modern replacement for fontcolor would use a span and a style (or class), e.g.:
function modernFontColor(str, color) {
return '<span style="color: ' + color + '">' + str + '</span>';
}
or
function modernFontClass(str, cls) {
return '<span class="' + cls + '">' + str + '</span>';
}
...where the class defines the styling.
So i am learning Javascript and trying to set and retrieve a cookie, my code all looks to be ok but there is obviously a problem here.
function init()
{
var panel = document.getElementById("panel");
var user = escape("Dan, 000456");
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
document.cookie = "myData=" + user + ";" + "expires=" + expiry.toGMTString() + ";";
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
When I look in the results they are not what I am expecting to see:
Cookie String:undefined
Split List:undefined
User Name:undefined
User Account:undefined
Your main issue is now that you have corrected your syntax errors is that the following line:
var user = escape("Dan, 000456");
note: I believe the escape function is now deprecated?
change your javascript to this and make sure your browser allows cookies:
function init(){
var panel = document.getElementById("panel");
var user = ["Dan, 000456"]; //<--change #1
var expiry = new Date();
expiry.setTime(expiry.getTime() + (7*24*60*1000) );
//change #2 below added the array index of user to set the cookie value for myData
document.cookie = "myData=" + user[0] + ";" + "expires=" + expiry.toGMTString();
if (document.cookie)
{
var cookieString = unescape(document.cookie);
var list = cookieString.split("=");
if (list[0] === "myData")
{
var data = list[1].split(",");
var userName = data[0];
var userAcct = data[1];
}
}
panel.innerHTML += "Cookie String:" + cookieString;
panel.innerHTML += "<br>Split List:" + list;
panel.innerHTML += "<br>User Name:" + userName;
panel.innerHTML += "<br>User Account:" + userAcct;
}
document.addEventListener("DOMContentLoaded",init, false);
Also make sure your html looks like this:
<div id="panel">Test</div>
You can remove the Test from the div in the html above if you want. The Test value should be replaced by values in your panel.innerHTML assignments.
var family = {
dad: 'Father',
mom: 'Mother',
son: 'Boy',
daughter: 'Girl'
}
for ( var person in family ) {
console.log('<li>' + 'the ' + person + ' is a ' + family[person] + '</li>')
}
I want to know what the best way to insert this into the DOM instead of logging it to the console. I want to use just JavaScript
Depends on what is already in the HTML. If you're simply adding exactly what you have, it wouldn't be a bad idea to just use:
var all_family = "";
for (var person in family) {
all_family += "<li>the " + person + " is a " + family[person] + "</li>";
}
document.getElementById("main_ul").innerHTML = all_family;
where "main_ul" is:
<ul id="main_ul"></ul>
Another option is:
var ul = document.getElementById("main_ul");
for (var person in family) {
var li = document.createElement("li");
li.innerHTML = "the " + person + " is a " + family[person];
main_ul.appendChild(li);
}
Something you might look at to help decide which to use: "innerHTML += ..." vs "appendChild(txtNode)"
Native, cross-browser DOM methods are the safest.
var list = document.createElement('li');
for (var person in family)
list.appendChild(
document.createTextNode('the person is a ' + family[person]) );
document.body.appendChild( list );
function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.