How to show table rows based on URL parameter - javascript

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' })

Related

Reading text in columns from HTML tables

I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:
<table id="country_LE_table" style = "display:none">
<tr>
<td>Japan</td>
<td>83.7</td>
</tr>
<tr>
<td>Switzerland</td>
<td>83.4</td>
</tr>
</table>
My Javascript is:
<script type="text/javascript">
function getLifeExpectancy() {
var Country = "<?php echo $Country ?>";
document.write(Country); // this gets read OK
var table = document.getElementById("country_LE_table");
var tr = table.getElementsByTagName("tr");
document.write(tr.length); document.write("<br>"); // works as expected
for (var i = 0; i < tr.length; i++) {
document.write(tr[i].innerHTML); document.write("<br>"); // works well up to here
// the following doesn't work
var td = tr[i].getElementsByTagName("td")[0];
if (td = Country) { //need td.fullHTML/value/fullText?
return tr[i].getElementsByTagName("td")[1]; // return the number
}
document.getElementById("demo").innerHTML = getLifeExpectancy();
</script>
If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.
Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
{
}

how do i write to an html from a javascript function?

i have a problem with my javascript and html
i was trying to write a html element using a function from my javascript
here's my code
function write();
{
for(var i=0;i<arr.length;i++)
{
document.write("<td>"+arr[i]+"</td><br>")
}
}
and code at my index.html, i want put that write inside my table row
<tr>
<script>write();</script>
</tr>
i have attached my javscript to my html document, but nothing happened
can u guys help me to put make that function work??
thanks guys!!
As per your question description, for writing html or dom elements say, you need to first create element(until you already have in which case you can use document.getElementById()) and then add text.
For creating:
# Create new dom element
var td = document.createElement("td");
Adding text:
td.appendChild(document.createTextNode('hiii'))
In your case:
function write(){
var element;
for(var i=0;i<arr.length;i++) {
element = document.createElement("td");
element.appendChild(document.createTextNode(arr[i]));
}
}
Give your row an id like this:
<tr id="myRow">
</tr>
Also i would recommend you to implement the function call in your javascript file.
Try something like this:
window.onload = function(){
write();
};
function write(){
for(var i = 0; i < arr.length; i++){
document.getElementById("myRow").innerHTML += "<td>" + arr[i] + "</td><br>";
}
}
you can check html below:
<table>
<tr id="myid" >
</tr>
</table>
and javascript would be like this
var row = document.getElementById("myid");
var x = row.insertCell(0);
x.innerHTML="New cell";
HTML:
<table>
<tr id='row'></tr>
</table>
JS:
function write(arr) {
var row = '';
for (var i = 0; i < arr.length; i++) {
row += '<td>'+arr[i]+'</td>'
}
document.getElementById('row').innerHTML = row;
}
write(['a', 'b', 'c', 'd']);
working demo: http://jsfiddle.net/uhaEL/

Javascript - How do you set the value of a button with an element from an array?

<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);

Is there a way to display content on same page after a button is clicked?

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 +="&nbsp&nbsp";
}
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:&nbsp&nbsp<input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:&nbsp&nbsp<input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Please Enter a character:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<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;

question regarding javascript;Html generation and search current webpage for tags

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.

Categories