I apologize if this kind of question has already been asked but I have looked through "Related Questions" and I don't think anything in here matches with mine, so please bear with me as I try to present my problem and how am I going to go about this, so here I go.
Okay, I will refer you my screenshot. Two of my tables have been generated by using Javascript and one is static and I didn't comment out the tbody tags within a listModulesWithinScene table.
http://img852.imageshack.us/i/haildstabletable.jpg/ (click in the link to view the image)
Here's my cut-down version of my HTML code for those who are interested. I'm pretty much new to this website, even though I do lurk through here from search engine (Google).
<?xml version="1.0" encoding="UTF-8" ?>
<!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">
<head>
<title></title>
<link href='http://fonts.googleapis.com/css?family=Josefin+Sans:100,regular' rel='stylesheet'
type='text/css' />
<link href="cssHomeAutomaionInterface.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="Scripts/SwitchContent.js"></script>
<script type="text/javascript" src="Scripts/ScrollingImagesInHeader.js"></script>
<script type="text/javascript" src="Scripts/XMLReaderWriter.js"></script>
<script type="text/javascript" src="Scripts/Main.js"></script>
<script type="text/javascript" src="Scripts/PageSpecific/Home.js"></script>
</head>
<body>
<!-- ... -->
<div id="home" class="container">
<div id="menuHome" class="submenu">
</div>
<div id="contentHome" class="content">
<h1>Home Page</h1>
<div id="moduleListArea">
<table id="listModules" class="data">
<caption>Lights and Devices</caption>
<thead>
<tr>
<th style="width: 100px;">Module ID#</th>
<th>Module Name</th>
<th style="width: 60px;">Status</th>
<th style="width: 150px">Action</th>
</tr>
</thead>
<!--<tbody>
<tr style="color: Green;" title="Dimmer">
<th>AB.CD.EF</th>
<td>2x Floor Lamp</td>
<td>75%</td>
<td>
Toggle
<div style="float: right;">
<input style="width: 40px;" id="module1" value="75" />
Set
</div>
</td>
</tr>
<tr style="color: Blue;" title="Switch">
<th>AB.CD.EE</th>
<td>Bedside Fan</td>
<td>ON</td>
<td>
Toggle
</td>
</tr>
</tbody>-->
</table>
</div>
<div id="sceneListArea" style="width: 50%; float: left;">
<table id="listScenes" class="data">
<caption style="text-align: left;">Scenes</caption>
<thead>
<tr>
<th>Scene Name</th>
<th style="width: 80px">Action</th>
</tr>
</thead>
<!--<tbody>
<tr>
<td>Welcome Home</td>
<td>Toggle</td>
</tr>
<tr>
<td>All Lights Off</td>
<td>Toggle</td>
</tr>
</tbody>-->
</table>
</div>
<div id="modulesWithinSceneListArea"
style="width: 50%; float: right;">
<table id="listModulesWithinScene" class="data">
<caption style="text-align: right;">Lights and Devices Within Scene</caption>
<thead>
<tr>
<th style="width: 100px;">Module ID#</th>
<th>Scene Name</th>
<th style="width: 50px">Level</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>2x Floor Lamp</td>
<td>50%</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- ... -->
</body>
</html>
</code>
Now, let me go ahead and describe my problem.
So anyway, I want to call a function that's in the part of the code:
// Create a new anchor tag and name it "List."
var a_set = document.createElement("a");
a_set.href = "javascript:ListAllModulesWithinScene(listScenes_row" + r +
"_toggle";<br />
a_set.id = "listScenes_row" + r + "_set";
a_set.appendChild(document.createTextNode("List"));
I want javascript:ListAllModulesWithinScene(...) that is inside quotes to call the function (ListAllModulesWithinScene(sceneName)) in PageSpecific/Home.js, but nothing happens if I click the List link; so far, it's not working. This is the function that I'm trying to call.
function ListAllModulesWithinScene(sceneName)
{alert("test");
/* The part of the code that I took out fills up the table with the list of modules
that are part of the scene, each module having different levels/settings. */
}
The expected result is that I want to see the alert message box just to make sure it works before I call out the code to generate the rows of data like say...
function ListAllModulesWithinScene(sceneName)
{
/*listModulesWithinScene = document.getElementById("listModulesWithinScene");
// Delete the tbody tag if it does not exist and create a enw tbody tag.
if(listModulesWithinScene.getElementsByTagName("tbody") != null)
listModulesWithinScene.removeChild("tbody");
var listModulesWithinScene_tBody = document.createElement("tbody");
var xmlRows = xmlObj.childNodes[2].getElementsByTagName("Scene");
for (var r = 0; r < xmlRows.length; r++)
{
if (xmlRows[r].getAttribute("name") == sceneName)
{
var moduleRow = xmlRows[r].getElementsByTagName("Module");
if (moduleRow.length > 0)
{
var row = document.createElement("tr");
for (var msr = 0; msr < moduleRow.length; msr++)
{
var moduleRow2 = xmlObj.childNodes[1].getElementsByTagName("Module");
for (var mr = 0; mr < xmlRow2.length; mr++)
{
if (moduleRow[mr].getAttribute("id") ==
xmlObj.childNodes[1].childNodes[mr].getAttribute("id"))
{
var td_id = document.createElement("th");
td_id.appendChild(
document.createTextNode(moduleRow.getAttribute("id")));
td_id.setAttribute("id", "listModulesFromScene_row" + r +
"_id");
row.appendChild(td_id);
var td_name = document.createElement("td");
td_name.appendChild(
document.createTextNode(moduleRow2.getAttribute("name")));
td_name.setAttribute("id", "listModulesFromScene_row" + r +
"_name");
row.appendChild(td_name);
var td_level = document.createElement("td");
td_level.appendChild(
document.createTextNode(moduleRow.getAttribute("level")));
td_level.setAttribute("id", "listModulesFromScene_row" + r +
"_level");
row.appendChild(td_level);
}
}
}
}
}
}
listModulesWithinScene_tBody.appendChild(row);
listModulesWithinScene.appendChild(listModulesWithinScene_tBody);*/
}
In order to help get a better ideal of how my tables are generated, I want to post my entire code. I could provide more details about my problem but that's all I can provide for now.
This is the XMLReaderWriter.js file that I currently have.
/*
When it comes to loading and saving an XML file, it helps to try to keep the XML file organized
and well-formed, so it's best to not to modify the XML file UNLESS you know what you're doing.
The structure of an XML file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<HomeAutomationInterface>
<Setup>
<Location longitude="" latitude="" />
</Setup>
<Modules>
<!-- The first row is an example. -->
<Module id="1" name="module name" level="ON" type="dimmer">
<!-- ... -->
</Modules>
<Scenes>
<!-- the first row is an example. It can contain multiple modules. -->
<scene name="Scene Name">
<module id="1" level="50">
<module id="2" level="60">
<!-- ... -->
</scene>
<!-- ... -->
</Scenes>
<Timers>
<!-- The following four rows are an example. For DST, sunrise and sunset
is dependent in longitude and latitude. How this works is this:
1. Go to this website and enter your address information.
http://stevemorse.org/jcal/latlon.php
2. Go here and enter your today's date, followed by longitude and latitude,
and time zone: http://www.weatherimages.org/latlonsun.html
3. You should get your information related to sunrise and sunset. It should
look like this:
Thursday
10 March 2011 Universal Time - 5h
SUN
Begin civil twilight 06:30
Sunrise 06:54
Sun transit 12:48
Sunset 18:42
End civil twilight 19:06
Now that's how you get your times for your sunruse and sunset.
-->
<timer name="Timer Name 1" type="regular">
<regular time="hour:minute:second:millisecond">
<module id="1" level="50">
<!-- ... -->
</regular>
</timer>
<timer name="Timer Name 2" type="regular">
<regular time="hour:minute:second:millisecond">
<scene name="Scene Name">
<!-- ... -->
</regular>
</timer>
<timer name="Timer Name 3" type="DST">
<DST occour="sunrise|sunset" offsetDir="later|sooner"
offset="hour:minute:second:millisecond">
<module id="1" level="75">
<!-- ... -->
</DST>
</timer>
<timer name="Timer Name 4" type="DST">
<DST occour="sunrise|sunset" offsetDir="later|sooner"
offset="hour:minute:second:millisecond">
<scene name="Scene Name">
<!-- ... -->
</DST>
</timer>
<!-- ... -->
</Timers>
</HomeAutomationInterface>
It's a long documentation, but it helps to understand what this XML structure is all about.
*/
// Not for Internet Explorer 6 or below.
var xmlDoc;
var xmlObj;
// For HTML tables (<table>)
var listModules;
var listScenes;
var listModulesWithinScene;
// For HTML text boxes
var inputLongitude;
var inputLatitude;
function LoadXML()
{
// ActiveXObject will have to be checked first to see if it's defined. Otherwise, if you
// try to check XMLHttpRequest first, even if Internet Explorer supports it, you will get
// "Access Denied" in Internet Explorer and perhaps not in Firefox.
if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load("HomeAutomationInterface.xml");
PopulateFromXML();
}
else
{
// If this is the only code in this function, then you will need to put all your
// project in the server, since Internet Explorer has a "Same Origin Policy" which
// I believe that the open method with "GET" causes a problem in Internet Explorer
// but did not cause a problem in Firefox. In order to rectify the problem, the code
// inside if(window.ActiveXObject) makes use of ActiveX.
xmlDoc = new XMLHttpRequest();
xmlDoc.open("GET", "HomeAutomationInterface.xml", null)
xmlDoc.send(null);
if (xmlDoc.status == 200)
{
xmlDoc = xmlDoc.responseXML;
PopulateFromXML();
}
}
}
function PopulateFromXML()
{
listModules = document.getElementById(
"listModules").getElementsByTagName("tbody");
// Gather the text fields for location data.
inputLongitude = document.getElementById("inputLongitude")
inputLatitude = document.getElementById("inputLatitude")
// Firefox's DOM Parser treats whitespaces as text nodes, including
// line breaks.
removeWhitespace(xmlDoc.documentElement);
// Send the document's root element to the XML Object variable.
xmlObj = xmlDoc.documentElement;
// Perform the checks and populate the tables
// and any other elements that are needed.
if (xmlObj.tagName == "HomeAutomationInterface")
{
// Check to be sure the first node is the "Setup" node. It contains the
// location node.
if ((xmlObj.childNodes[0].tagName == "Setup") &&
(xmlObj.childNodes[0].childNodes[0].tagName == "Location"))
{
// Copy the data from one of the attributes to the respective text boxes.
inputLongitude.value = xmlObj.childNodes[0]
.childNodes[0].getAttribute("longitude");
inputLatitude.value = xmlObj.childNodes[0]
.childNodes[0].getAttribute("latitude");
}
// The second node within the root element is Modules node.
// This will be implemented.
if (xmlObj.childNodes[1].tagName == "Modules")
{
//TODO: Implement the XML-to-Table translation that gets info
// about modules.
listModules = document.getElementById("listModules");
var listModules_tBody = document.createElement("tbody");
var xmlRows = xmlObj.childNodes[1].getElementsByTagName("Module");
for (var r = 0; r < xmlRows.length; r++)
{
var xmlRow = xmlRows[r];
var row = document.createElement("tr");
var td_id = document.createElement("th");
td_id.appendChild(document.createTextNode(xmlRow.getAttribute("id")));
td_id.setAttribute("id", "listModules_row" + r + "_id");
row.appendChild(td_id);
var td_name = document.createElement("td");
td_name.appendChild(document.createTextNode(xmlRow.getAttribute("name")));
td_name.setAttribute("id", "listModules_row" + r + "_name");
row.appendChild(td_name);
var td_level = document.createElement("td");
td_level.appendChild(document.createTextNode(xmlRow.getAttribute("level")));
td_level.setAttribute("id", "listModules_row" + r + "_level");
row.appendChild(td_level);
if (xmlRow.getAttribute("type") == "dimmer")
{
row.style.color = "Green";
// Create a new table cell for a dimmer. This will include a toggle,
// a text box, and a set button.
var td_dimmer = document.createElement("td");
// Create a new anchor tag and, set the href to #, and name it "Toggle."
var a_toggle = document.createElement("a");
a_toggle.href = "#";
a_toggle.id = "listMoudles_row" + r + "_dimmer_toggle";
a_toggle.appendChild(document.createTextNode("Toggle"));
td_dimmer.appendChild(a_toggle);
// Create a new div element to hold a text box and a set button.
var div_floatright = document.createElement("div");
div_floatright.style.float = "right";
// Create a new text box and append it to the div element.
var input_level = document.createElement("input");
input_level.type = "text";
input_level.name = "listModules_row" + r + "_inputLevel";
input_level.id = "listModules_row" + r + "_inputLevel";
input_level.style.width = "40px";
div_floatright.appendChild(input_level);
// Create a new anchor tag, set the href to #, and name it "Set."
var a_set = document.createElement("a");
a_set.href = "#";
a_set.id = "listMoudles_row" + r + "_dimmer_set";
a_set.appendChild(document.createTextNode("Set"));
div_floatright.appendChild(a_set);
// Append the div element to the table cell.
td_dimmer.appendChild(div_floatright);
// Finally, append the table cell to the row.
row.appendChild(td_dimmer);
}
else if (xmlRow.getAttribute("type") == "switch")
{
row.style.color = "Blue";
// Create a new table cell for a dimmer. This will include a toggle,
// a text box, and a set button.
var td_switch = document.createElement("td");
// Create a new anchor tag and, set the href to #, and name it "Toggle."
var a_toggle = document.createElement("a");
a_toggle.href = "#";
a_toggle.id = "listMoudles_row" + r + "_dimmer_toggle";
a_toggle.appendChild(document.createTextNode("Toggle"));
td_switch.appendChild(a_toggle);
row.appendChild(td_switch);
}
else
{
row.style.color = "Black";
row.appendChild(document.createTextNode("No actions available."));
}
listModules_tBody.appendChild(row);
}
listModules.appendChild(listModules_tBody);
// Uncomment this code and run the example.
//alert(listModules_row0_name.textContent);
}
// The third node within the root element is Scenes node.
// You need modules in order for scenes to work.
// This will be implemented.
if (xmlObj.childNodes[2].tagName == "Scenes")
{
listScenes = document.getElementById("listScenes");
var listScenes_tBody = document.createElement("tbody");
var xmlRows = xmlObj.childNodes[2].getElementsByTagName("Scene");
for (var r = 0; r < xmlRows.length; r++)
{
var xmlRow = xmlRows[r];
var row = document.createElement("tr");
var td_name = document.createElement("td");
td_name.appendChild(document.createTextNode(xmlRow.getAttribute("name")));
td_name.setAttribute("id", "listScenes_row" + r + "_name");
row.appendChild(td_name);
row.appendChild(td_name);
var td_actions = document.createElement("td");
// Create a new anchor tag and name it "Toggle."
var a_toggle = document.createElement("a");
a_toggle.href = "#";
a_toggle.id = "listScenes_row" + r + "_toggle";
a_toggle.appendChild(document.createTextNode("Toggle"));
// Create a new anchor tag and name it "List."
var a_set = document.createElement("a");
a_set.href = "javascript:ListAllModulesWithinScene(listScenes_row" + r +
"_toggle";
a_set.id = "listScenes_row" + r + "_set";
a_set.appendChild(document.createTextNode("List"));
td_actions.appendChild(a_toggle);
td_actions.appendChild(a_set);
row.appendChild(td_actions);
listScenes_tBody.appendChild(row);
}
listScenes.appendChild(listScenes_tBody);
}
// The last element is the Timers node.
// This will either activate the scene or turn on, off,
// dim, brighten, or set the light level of the module if
// it is the light module or turn on or off the appliance
// module. This will be implemented.
if (xmlObj.childNodes[3].tagName == "Timers")
{
//TODO: Implement a XML-to-Table parser that parses the XML data
// from the timers tag into the timer table.
}
}
}
// I stumbled across http://www.agavegroup.com/?p=32 and I borrowed the code from
// http://stackoverflow.com/questions/2792951/firefox-domparser-problem
// It took me a week to debug all my code until I find out what's going on with Firefox's
// DOM Inspector.
function removeWhitespace(node)
{
for (var i = node.childNodes.length; i-- > 0; )
{
var child = node.childNodes[i];
if (child.nodeType === 3 && child.data.match(/^\s*$/))
node.removeChild(child);
if (child.nodeType === 1)
removeWhitespace(child);
}
}
And now as for my background information, I'm doing this as my project for COP2822 (Scripting for the Web), so it's only Javascript and not server-side, so I have endured a lot of pain, but was able to make it through, so my experience with Javascript is well worth it in the end. I did have some experience with Javascript before I take COP2822, though.
Welcome to SO. Considering you copy pasted your code
a_set.href = "javascript:ListAllModulesWithinScene(listScenes_row"
+ r + "_toggle)";//<br />
You had a weird br tag in the middle of your js code and you had a missing ) in the function call.
If you still have issues, post and I'll try to discuss. I suggest getting a browser or extension to your browser that supplies a javascript console. In my opinion it's invaluable to debugging.
i think you want quotes (escaped) around the sceneName parameter value:
a_set.href = "javascript:ListAllModulesWithinScene(\"listScenes_row" + r + "_toggle\")";
Related
It is the first time I use firebase and javascript, I am making a table where it shows me the data from a database in real time. For this, I'm pulling the data like this:
function getSonido() {
var firebase = "https://iotplatform-11dca-default-rtdb.firebaseio.com/users/awsBewgkSMcqiINzOoFUiUe9D6r1/data_widget/sensor/sonido.json";
var sensores = new EventSource(firebase);
sensores.addEventListener('put', function(e) {
var json = JSON.parse(e.data);
console.log(json);
if (json.path == "/") {
tbody = document.getElementById("tbody_sonido");
for (var key in json.data) {
var tr = document.createElement("tr");
var td_sensor = document.createElement("td");
var td_sonido = document.createElement("td");
var input_sonido = document.createElement("input");
var td_ruta = document.createElement("td");
var td_button = document.createElement("td");
input_sonido.type = "number";
input_sonido.id = key;
input_sonido.readOnly = true;
input_sonido.disabled = true;
td_sensor.innerHTML = json.data[key].name;
td_ruta.innerHTML = "/" + key + "/sonido";
td_button.innerHTML = '<button class="btn btn-danger delete" id="' + key + '" type="button">Borrar</button>';
td_sonido.appendChild(input_sonido);
tr.appendChild(td_sensor);
tr.appendChild(td_sonido);
tr.appendChild(td_ruta);
tr.appendChild(td_button);
tbody.appendChild(tr);
document.getElementById(key).value = json.data[key].sonido;
}
} else {
s = json.path.split("/");
console.log(s[1]);
console.log(json.data);
document.getElementById(s[1]).value = json.data;
}
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Widgets</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script type="text/javascript" src="/static/js/get_sensores.js"></script>
</head>
<body>
<h1>Sound sensors</h1>
<table id="table_sonido" class="table table-striped">
<thead id="thead_sonido">
<tr>
<th>Name</th>
<th>Value</th>
<th>Route</th>
</tr>
</thead>
<tbody id="tbody_sonido">
<!-- One row will be added for each item in the json file -->
</tbody>
</table>
<script>
document.onload = getSonido();
</script>
</body>
</html>
Place a button on each item in the table that is added, all buttons have the same class but the ID value of each button will depend on the item saved in firebase, in console the button is displayed like this
I am trying to remove the element that I click to delete, for that I must get the value of the ID of the button, investigating found that I could use console.log(document.getElementsByClassName("delete")[0].id); but there I am specifying which button I want to get the value from, which is not correct.
Looking for I saw that some used the jQuery library but don't explain much the process.
While I found a solution to that first problem, I was working with the way to eliminate the element, in the documentation comes something like this curl -X DELETE \ 'https://[PROJECT_ID].firebaseio.com/locations.json' so try using something like this:
const request = new Request('https://iotplatform-11dca-default-rtdb.firebaseio.com/users/awsBewgkSMcqiINzOoFUiUe9D6r1/data_widget/sensor/sonido/0x459ece7.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()
This would run with an onclick within a function but it also does nothing, try the same using the SDK, perform the configuration and use remove(), to remove but I also did not work and it marked me error or simply did not run.
I hope I have explained and I know that it is very extensive but I have already been several days and I have looked a lot for how to do this firebase even in videos but I just do not get the result I need and I have been trying everything for several days but I simply can not make it work.
I hope you can help me
Currently the page is accessed using a link, for instance help.html?show=charInPw.
The table is written in the following manner:
<table>
...
<tbody class="table-body">
<tr class="pwLen"><td colspan="5" class="subheading">Password Length</td></tr>
<tr class="pwLen"><td class="first">Minimum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="pwLen"><td class="first">Maximum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td colspan="5" class="subheading">Characters in Password</td></tr>
<tr class="charInPw"><td class="first">Minimum numeric characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td class="first">Minimum alphabetic characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
...
The CSS is as follows:
table tbody tr{
text-align: center;
display: none;
}
(There are also trs in thead and they are always shown by default.)
Then I have some Javascript code as follows (jQuery is not an option):
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
for (i = 0; i < document.getElementsByClassName(c); i++)
document.getElementsByClassName(c)[i].style.display='table-row';
</script>
However I am not able to get my rows to show.
How should I change the code on the page to show only the rows referenced by the show parameter?
Edit #1: As a test I did the following hard-coding but it didn't work too!
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
var trs = document.getElementsByClassName('pwLen');
for (i = 0; i < trs.length; i++)
trs[i].style.display='table-row';
</script>
Edit #2: I have combined two solutions below into one - please see https://jsfiddle.net/tea45p2o/. The demo output shown is what I want, however I am not able to see that when I save the file and open the page in my browser. What is going on?
With much help from BJohn and MrJ, I have come up with my solution as follows:
<script>
function show() {
var url = new URL(window.location.href);
var c = '.' + url.searchParams.get("show");
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
}
</script>
Then, I changed my <body> to
<body onLoad="show();">
Use below code:
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
You also need to append dot (.) with class name, which you are getting from the URL.
Please find the fiddle here
ŷou are missing to place .length
for (i = 0; i < document.getElementsByClassName(c).length; i++)
But I think it would be more readable on this way
for(let TR_x of [... document.getElementsByClassName(c) ]) {
TR_x.style.display='table-row';
}
but I definitely prefer
document.querySelectorAll('.'+c).forEach(trX=>{ trX.style.display='table-row' })
I am trying to get my content to display on the same page as my button. But when i enter the values and press display the square i am forming is displayed on a new white webpage.
I ask the user to enter two values (height and width), I also ask for a character to form the border of the square, but i have not been able to do that part yet so i just hard coded a # character in for the border in the meantime
What i would like to know is how to display my square on the same page and not in a seperate page.
I use an external JavaScript file: Here is its code. Its named "SquareScript.js":
function Display()
{
var a = document.getElementById("value1").value;
var b = document.getElementById("value2").value;
var outputText = "";
for (var i = 0; i < a; i++)
{
outputText += "#";
}
outputText +="<br>";
for (var r = 0; r < b; r++)
{
outputText += "#";
for(var p = 0; p < a-2; p++)
{
outputText +="  ";
}
outputText += "#";
outputText +="<br>";
}
for (var i = 0; i < a; i++)
{
outputText += "#";
}
}
Here is my webpages code:
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "Assignment3.css">
<style>
table {background-color:white;color:black;}
body {background-image: url('squares.png');}
</style>
</head>
<body>
<div class = "heading">
<h1><img src = "Interested.png" width = 100px height = 100px></img>WELCOME TO BUILD A SQUARE</h1>
</div>
<script src = "SquareScript.js">
</script>
<table>
<tr>
<td>
Please Enter value number 1:  <input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:  <input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Please Enter a character:         <input type = "text" id = "character">
</td>
</tr>
<tr>
<td>
<button onclick = "Display()">Display</button>
</td>
</tr>
<div id="output" style = "background-color:blue;"><script>
document.getElementById("output").innerHTML(outputText);
</script></div>
</table>
</body>
</html>
Any useful tips will be appreciated and please consider the fact that I am still new to web development so my code is obviously very basic. Please let me know if you require anything more of me.
The way document.write() works is that when it's called outside the HTML page, it automatically creates a new document and writes into that (see the documentation). This is what's going on in your case: the function is called outside of the HTML (in SquareScript.js) and so it's making a new document, which is the "new white webpage" you're seeing.
You could solve this problem by calling document.write() from within the HTML page. Or you could forego using document.write() and instead reference an element on the existing page (a more flexible solution). By creating a new element in your HTML where the output of your functions should appear (like <div id="output"></div>), you can use document.getElementById("output") to put your script's output into that element.
You don't need to call this every time you want to add content. Instead, create a new variable to hold your output text as you generate it.
var outputText = "";
Then as you go through your loops, you can add to outputText:
for (var i = 0; i < a; i++) {
outputText += "#";
}
Then after all your loops are complete, you can insert the content into the output div by making the following function call as the last thing in your display() function:
document.getElementById("output").innerHTML(outputText);
Do not use document.write. Create <div id="result"></div> on your page and place your output there. You should create a string variable containing your HTML output. Then you can display this HTML using the following code:
document.getElementById("result").innerHTML = my_html_output;
Ok, I'm new to javascript (learning quickly though). I've been able to cobble together some code which does a couple of things.
Opens/reads an excel file (local now but will be on server). Get
cell A1 (will always be a #) - variable repCount.
Writes cells A2-A33 to a table in html (hard coded start and stop)
Now what I would it to do is
take the repCount variable as the ending row in the writing part - dynamic stop point
write it to an array that I can manipulate (should be globally available).
Here's my code so far:
<script language="javascript" >
// Open the spreadsheet and get the count of reps
function GetData(cell,row)
{
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("SOMEFILE.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var repCount = excel_sheet.Cells(cell,row).Value;
document.getElementById('div1').innerText = repCount;
}
// open spreadsheet and populate table with representatives
var excelApp=null, excelFile=null, excelSheet=null;
var filename = "SOMEFILE.xlsx";
function initExcel(filename)
{
excelApp = new ActiveXObject("Excel.Application");
excelFile = excelApp.Workbooks.Open(filename);
excelSheet = excelApp.Worksheets('Sheet1');
}
function myShutdownExcel()
{
excelApp.Quit();
excelApp=null;
excelFile=null;
excelSheet=null;
}
function myGetData(column, row)
{
return excelSheet.Cells(column, row).Value;
}
function byId(e) {return document.getElementById(e);}
function myOnLoad2()
{
var numRows = 33, numCols = 1;
var tBody = byId('dataTableBody');
var rowIndex, colIndex, curVal;
var curRow, curCell, curCellText;
initExcel(filename);
for (rowIndex=2; rowIndex<=numRows; rowIndex++)
{
curRow = document.createElement('tr');
for (colIndex=1; colIndex<=numCols; colIndex++)
{
curVal = myGetData(rowIndex, colIndex);
curCell = document.createElement('td');
curCell.setAttribute('title', 'The value of cell [' + rowIndex + ',' + colIndex +']\nis: ' + curVal);
curCellText = document.createTextNode(curVal);
curCell.appendChild(curCellText);
curRow.appendChild(curCell);
}
tBody.appendChild(curRow);
}
myShutdownExcel();
}
</script>
</head>
<body>
<p> </p>
<div style="background: #009955; width:'100%';" align="center">
<font color="#000080" size="12pt">
<b>Get data from excel sheets</b>
</font>
</div>
<center>
<p> </p>
<div id="div1" style="background: #DFDFFF; width:'100%';" align="center">
To start the statistics page - Click the button below
</div>
<input type="button" value="Start" onClick="GetData(1,1);" />
<input type="button" value="Next" onClick="myOnLoad2()" />
</center>
<b>Get data from excel sheets</b>
<table id='dataTable'>
<tbody id='dataTableBody'>
</tbody>
</table>
</body>
</html>
Am I on the right track? I can only use javascript so don't try pointing me to jQuery or PHP. Can anyone help or point me to a good resource, I do want to learn this but syntax and me...not such good friends. Once I see an example I'm pretty good about figuring out how to adapt it but getting it into an array has boggled me for the last week. Thanks in advance.
Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.