Change Background javascript function not working - javascript

The code (below) seems to compile without any errors, but the "changebackground" function isn't working. it does nothing when you click on it.
I don't think there is a problem with Syntax, but cant be sure. There are no errors, just no response when i click on the cell.
"MyClick" works, bu t"ChangeBackground" doesn't.
Any thoughts??
<html><body>
<head>
<style>
table,th
{
border:1px solid black
font-size: 15px;
font-family: Arial;
font-weight: bold;
empty-cells: show;
}
</style>
<style>
td
{
font-size: 10px;
font-weight: normal;
font-family: Arial;
border:1px solid black;
empty-cells: show;
align = "middle;"
}
</style>
<style>
p
{
font-size: 18px;
font-weight: bold;
font-family: Arial;
}
</style>
<style>
a.1{ text-decoration:none;color:WindowText}
</style>
<style>
#header{ display:block;top:0px;left:0px;width:100%;height: 112px;position:fixed;background-color: #ffffff;border:1px solid #888;}
</style>
<style>
#content{ margin:113px 0px 0px 0px;display:block;border:1px solid #888;}
</style>
<script type="text/javascript"> function myClick(args) { window.clipboardData.setData('text',args.toString()); }</script>
<script type="text/javascript"> function changeBackground() {document.getElementById(cellID).style.borderColor = "2px solid red"; }</script>
</head>
<p> Scanned Samples </p> <table></table></div> <p> Rack: 202771 - _SMEYER_IND_AC_2D-02 </p>
<table>
<thead>
<tr>
<font size = "10"> </font>
<th> </th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
</tr>
</thead>
<td> <font size = "2"><b>A</b></td>
<td><a class = "1" href = "#abcd"onclick="javascript:myClick('202772')"><center>A1<br>0<br>(202772)</center></td>
<td id = "Cell9"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202780') "; javascript:changeBackground('Cell9')"> <center> A2<br>0<br>(202780)</center> </td>
<td id = "Cell17"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202788') "; javascript:changeBackground('Cell17')"> <center> A3<br>0<br>(202788)</center> </td>
<td id = "Cell25"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202796') "; javascript:changeBackground('Cell25')"> <center> A4<br>0<br>(202796)</center> </td>
<td id = "Cell33"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202804') "; javascript:changeBackground('Cell33')"> <center> A5<br>0<br>(202804)</center> </td>
<td id = "Cell41"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202812') "; javascript:changeBackground('Cell41')"> <center> A6<br>0<br>(202812)</center> </td>
<td id = "Cell49"><a class = "1" href = "#abcd"onclick=" javascript:myClick('202820') "; javascript:changeBackground('Cell49')"> <center> A7<br>0<br>(202820)</center> </td>
</tr>
</table>
</body></html>

You're calling changeBackground with parameters when the function definition didn't have it. Here's an example
javascript:changeBackground('Cell9')"
Here is your function definition
function changeBackground() {
document.getElementById(cellID).style.borderColor = "2px solid red";
}
Try changing that to
function changeBackground(cellID) {
document.getElementById(cellID).style.borderColor = "2px solid red";
}
Also, this is pretty bad form too. You should prefer stylesheets over style tags, and you have a bunch of them. Same thing with the script tags. Please place them in an external JavaScript file.
Also, you are using inline javascript too often like this example
onclick=" javascript:myClick('202812') "; javascript:changeBackground('Cell41')"
This makes the HTML really difficult to read. You should instead use event listeners and place them in your JavaScript file.
Also, the center and font tags are not supported in HTML5.

Related

I can't figure out why the javascript generated <tr> elements aren't being styled by my stylesheet

I'm trying to make a table with the background color alternating for every other row element. The styling seems to work for the row elements already in the html code, but when I generate some more rows using javascript, the new rows aren't styled and I can't figure out why. Any help would be appreciated.
/* class Definitions
*******************/
class ladder{
constructor(){
this.data;
}
async getLeaderBoard(){
try{
const ret = await fetch(`https://cors-anywhere.herokuapp.com/https://aoe2.net/api/leaderboard?game=aoe2de&leaderboard_id=3&start=1&count=10`);
this.data = await ret.json();
}
catch(error){
console.log(error);
}
}
}
//table DOM functions
const renderCell = player => {
const markup = `
<tr class="player-entry">
<td>${player.rank}</td>
<td>${player.rating}</td>
<td><a href= "">${player.name}</td>
<td>${player.games}</a></td>
<td>${Math.round(100*player.wins/player.games)/100}</td>
</tr>`;
document.querySelector('.leaderboards').insertAdjacentHTML('beforeend', markup);
};
const renderTable = leaderBoard =>{
leaderBoard.forEach(renderCell);
}
/***********************
/*MAIN
/***********************/
/*store data in window*/
const state = {};
/*
* Fetch the data and save in state array
*/
const dataFetcher = async () =>{
//store the ladder object in state array
state.AOELadder = new ladder();
//load ladder from api
await state.AOELadder.getLeaderBoard();
//update to UI
renderTable(state.AOELadder.data.leaderboard);
}
dataFetcher();
.leaderboards{
width:80%;
text-align: left;
margin-left:3rem;
margin-top:3rem;
line-height: 1.4rem;
border:#888888 solid 1px;
border-collapse: collapse;
}
.leaderboards .title{
border-bottom:#888888 solid 1px;
background:#222222;
color:#fff;
height:2rem;
}
.leaderboards a{
text-decoration: none;
color:#fff;
}
.leaderboards .player-entry{
background: #999999;
border-bottom:#888888 solid 1px;
color:#fff;
}
.leaderboards .player-entry:nth-child(odd){
background: #222222;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Practice Fetching API Data </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="leaderboards">
<tr class="title">
<th>Rank</th>
<th>Rating</th>
<th>Name</th>
<th>Games</th>
<th>Win Rate</th>
</tr>
<tr class="player-entry">
<td>565</td>
<td>1500</td>
<td>dummy-entry</td>
<td>1000</td>
<td>55%</td>
</tr>
<tr class="player-entry">
<td>565</td>
<td>1500</td>
<td>dummy-entry</td>
<td>1000</td>
<td>55%</td>
</tr>
<tr class="player-entry">
<td>565</td>
<td>1500</td>
<td>dummy-entry</td>
<td>1000</td>
<td>55%</td>
</tr>
</table>
<script type="text/javascript" src= "./main.js"></script>
</body>
</html>
The table tag automatically appends tbody element (TABLE must have one or more TBODY elements) to wrap the rows. Therefore, you need to add the row inside the body in order to determine alternation.
Just update your inserting script to this:
document.querySelector('.leaderboards').getElementsByTagName('tbody')[0].insertAdjacentHTML('beforeend', markup);

javascript prompt not showing

I am trying to create some code for a class that prompts the user to input three numbers then preforms some calculations to those numbers, the math is to square one number, multiply and multiply the number by PI then display them in the appropriate cells. Right now my onClick is not working and there is no prompt coming up for the user. I have the min and max functions in there so because it's required
Here is my code:
function promptForNumber(promptString, min, max) {
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
}
function populateRow(row) {
var number = promptForNumber("Enter your number");
row.cells[0].innerHTML = number;
row.cells[1].innerHTML = Math.pow(number, 2);
row.cells[2].innerHTML = (number / Math.PI).toFixed(4);
}
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a
valid number ")
}
table,
th,
tr,
td {
border-collapse: collapse;
}
table {
width: 80%;
margin: 10%;
}
th {
width: 33%;
border: 2px solid black;
justify-content: space-evenly;
height: 25px;
background-color: white;
}
td {
border: 1px solid black;
padding: 1%;
text-align: center;
background-color: greenyellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2</title>
</head>
<body>
<table>
<tr>
<th>Number</th>
<th>Squared</th>
<th>Divided by Pi</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
This looks like a homework question as you mentioned it's for a class, so I cannot give you the exact solution to the problem. However, I will point out what is wrong with your code at the moment.
You mentioned that your "onClick" is not working, but you do not have any onClick functions in this code.
You need to use the window.prompt() method to prompt for user input in JS.
You need to create a button that the user can press to receive an alert. Add an event listener onto this button that prompts the user to enter a number. You can get help with this here. After you have the number from the prompt stored in a variable, use that variable to perform the different mathematical operations, and have these be added to the table.
You have extra line in your prompt code, please correct your code like below:
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a valid number")
}
Also you must use standard method of prompt:
https://www.w3schools.com/jsref/met_win_prompt.asp
Infact you need to add the event listerner to listen for the click events.
May something like
<html lang="en">
<head>
<title>Assignment 2</title>
<style>
table, th, tr, td {
border-collapse: collapse;
}
table {
width: 80%;
margin: 10%;
}
th {
width: 33%;
border: 2px solid black;
justify-content: space-evenly;
height: 25px;
background-color: white;
}
td {
border: 1px solid black;
padding: 1%;
text-align: center;
background-color: greenyellow;
}
</style>
</head>
<body>
<table>
<tr>
<th>Number</th>
<th>Squared</th>
<th>Divided by Pi</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script>
function promptForNumber(promptString, min, max) {
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
}
function populateRow(row) {
var number = window.prompt("Enter your number");
var cell = row.getElementsByTagName("td");
cell[0].innerHTML = number;
cell[1].innerHTML = Math.pow(number, 2);
cell[2].innerHTML = (number / Math.PI).toFixed(4);
}
function isNotANumber(NaN) {
var isNotANumer = promptForAValidNumber("Please enter a valid number")
}
var table = document.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
console.log('rows', rows);
for (let i = 0; i < rows.length; i++) {
let currentRow = table.rows[i];
currentRow.addEventListener("click", function() {
populateRow(currentRow);
})
};
</script>
</body>
</html>
For me, the answer was putting the script tag of the JS file at the end of the HTML body tag.
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add a Todo</li>
<li>"list" - List all Todos</li>
<li>"delete" - Remove specific Todo</li>
<li>"quit" - Quit App</li>
</ul>
<script src="app.js"></script>
</body>
</html>

How to change class of specified <td>?

function change() {
var tds = document.getElementsByTagName("td");
var tds2 = tds.className;
console.log(tds);
for (var i = 0; i < tds.length; i++) {
if (tds[i].className === "marked") {
tds[i].className = "UNmarked";
} else {
tds[i].className = "marked";
}
}
}
function generTab(rows, cols) {
var html = "<table id='tb01'>";
for (var i = 1; i <= rows; i++) {
html += "<tr>"
for (var j = 1; j <= cols; j++) {
html += "<td class='marked' onclick='change()'>" + "</td>";
}
html += "</tr>"
}
return html + "</table>";
}
td.marked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: white;
}
td.UNmarked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: purple;
}
<div class="line">
Number of rows:
<input type="text" id="rows" />
</div>
<div class="line">
Number of cols:
<input type="text" id="cols" />
<span class="error"></span>
</div>
<input type="button" value="Generuj" id="gener" />
</div>
<div id="scene"></div>
I'm generating table by my own, and I want to change class of specified <td> by clicking on on it. The problem is that when I click on whichever <td> it is changing the classes of all of them, but I want to change that <td> class which I click.
May be you can do some thing like the following with a single class:
var tds = document.querySelectorAll("td");
tds.forEach(function(td){
td.addEventListener('click', function(){
this.classList.toggle('marked')
});
});
td {
border: 1px solid lightgray;
padding: 10px;
font-size: 20px;
}
.marked{
background-color: #4CAF50;
color: white;
}
<table>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>4</td><td>5</td><td>6</td>
</tr>
</table>
Add click event listeners to all the td elements and implement a simple onClick function which adds/removes the desired css class.
const tds = Array.from(document.querySelectorAll('td'));
const onClick = ({ target }) => {
tds.forEach(td => td === target ? td.classList.add('active') : td.classList.remove('active'))
}
tds.forEach(td => td.addEventListener('click', onClick));
.active {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</body>
</html>
The code you've written should be toggling the class of all tds in the document. I believe you're trying to change the class of the td that is being clicked. To do that, try something like (apologies in advance as I'm on my phone):
function change(e) {
let td = e.target;
if (td.classList.contains('marked')) {
td.className = 'UNmarked';
} else {
td.className = 'marked';
}
}
and be sure that that change is bound as the click event for each td.
If you can use jQuery...
$("td").click(function(){
$(this).toggleClass("marked")
.toggleClass("UNmarked");
});

Next button only brings the first image and stops

I have been trying to create a next and back buttons that go through the images one by one that are in the table.
But the next button, it only brings the first image and stops.
How can the same button "next" have the function of going through all the images?
<p id = "slider"></p>
<div id="galDiv">
<style>
table, th, td {
border: 1px solid black;}
</style>
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
<script>
document.getElementById("nxt").onclick = function()
{myFunction()};
function myFunction() {
var div = document.getElementById('galDiv');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling }
}
</script>
How can also create a back button ?
If you are trying to create a facebook like image viewer, you shouldn't use table element.
In order to create such thing you should create a div with container fixed side ,within this div you should have a div with floating images and then your button should change the right position of the inner div.
Or you could use a jquery library such as http://www.jacklmoore.com/colorbox
Your code does nothing. The next sibling to #galDiv is the <button>.
Is this what you wanted?
document.getElementById("nxt").onclick = myFunction;
function myFunction() {
var picture = [
"firstPicture",
"secondPicture",
"thirdPicture",
"fourthPicture"
];
var place = {
"firstPicture": 0,
"secondPicture": 1,
"thirdPicture": 2,
"fourthPicture": 3
};
var table = document.querySelector('table');
if (!table.className) {
table.className = "firstPicture";
}
var nextPicture = (place[table.className] + 1) % 4;
table.className = picture[nextPicture];
}
img[src="gallery/a.jpg"] {
border: 5px solid red;
}
img[src="gallery/k.jpg"] {
border: 5px solid green;
}
img[src="gallery/2.jpg"] {
border: 5px solid blue;
}
img[src="gallery/3.jpg"] {
border: 5px solid black;
}
table {
border-collapse: collapse;
position: absolute;
padding: none;
border: none;
}
#galDiv {
width: 113px;
height: 113px;
overflow: hidden;
position: relative;
}
.firstPicture {
left: 0;
}
.secondPicture {
left: -112px;
}
.thirdPicture {
left: -224px;
}
.fourthPicture {
left: -336px;
}
<p id = "slider"></p>
<div id="galDiv">
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
I added the curimg attribute to the slider. Read the script for yourself. You'll need to add in modulus arithmetic to round around the table entries. As for the 'prev' function. Figure out the same thing with a -1 when selecting the tdnode.
Don't forget to set the curimg attribute after you append the child.
Good luck!
<p id = "slider" curimg='1'></p>
<div id="galDiv">
<style>
table, th, td {
border: 1px solid black;}
</style>
<table>
<tr>
<td id="1"><img src="gallery/a.jpg" style="width:100px;height:100px;"></td>
<td id="2"><img src="gallery/k.jpg" style="width:100px;height:100px;"></td>
<td id="3"><img src="gallery/2.jpg" style="width:100px;height:100px;" ></td>
<td id="4"><img src="gallery/3.jpg" style="width:100px;height:100px;" ></td>
</tr>
</table>
</div>
<button id="nxt">NEXT</button>
<script>
document.getElementById("nxt").onclick = function()
{myFunction()};
function myFunction() {
//Get the slider, parse the int of the 'curimg' attribute
cid = document.getElementById('slider');
current_image = parseInt( cid.getAttribute('curimg') );
//Get the td of that id+1
tdnode = document.getElementById(current_image + 1);
//Clone the image childNode into the slider.
cid.appendChild( td.childNodes[0].cloneNode() );
}
</script>

Displaying JavaScript

I am still stuck on what should seem to be a simple concept. I have a very very simple javascript that just does some addition and I want to display the result on a web page. I have tried using a tag but that did not seem to do anything, an now I am trying to use the from the html but that is not working either. This seems like it should be such a simple thing to do but I am obviously missing something. Any help would be greatly appreciated. I have attached the html code, the script, and the css.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>The Lighthouse</title>
<link href="lhouse.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="title">
<p><img src="logo.jpg" alt="The Lighthouse" />
</p>
<p>The Lighthouse<br />
543 Oak Street<br />
Owensboro, KY 42302<br/>
(270) 555-7511
</p>
</div>
<div id="data_list">
<table rules="rows" cellspacing='0'>
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>2011-09-18</td>
<td id="amount1">125</td>
<td>Nina</td>
<td>Largent</td>
<td>88 Regal Lane<br />Willaimsburg, KY 40789</td>
</tr>
<tr class="yellowrow">
<td>2011-09-18</td>
<td id="amount2">75</td>
<td>Mike</td>
<td>Hunt</td>
<td>404 Barrow Street<br />London, KY 40742</td>
</tr>
<tr>
<td>2011-09-16</td>
<td id="amount3">50</td>
<td>Monica</td>
<td>Lang</td>
<td>743 Stawlings Drive<br />Danville, KY 40423</td>
</tr>
<tr class="yellowrow">
<td>2011-09-15</td>
<td id="amount4">150</td>
<td>William</td>
<td>McKnight</td>
<td>404 Barrow Street<br />Danville, KY 40423</td>
</tr>
<tr>
<td>2011-09-14</td>
<td id="amount5">250</td>
<td>Latrina</td>
<td>Hults</td>
<td>750 Whitehall Road<br />London, KY 40742</td>
</tr>
<tr class="yellowrow">
<td>2011-09-13</td>
<td id="amount6">50</td>
<td>Danny</td>
<td>Shamblin</td>
<td>123 Smith Street<br />Owensboro, KY 42303</td>
</tr>
</tbody>
</table>
</div>
<div id="totals">
<table rules="groups" cellspacing="1">
<thead>
<tr>
<th id="sumTitle" colspan="2">Summary</th>
</tr>
</thead>
<tbody>
<tr>
<th>Contributors</th>
<td id="contributions"> </td>
</tr>
<tr>
<th>Amount</th>
<td id="amount"> </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
__
// JavaScript Document
window.onload = function ()
{
//find the div tags called amount1, amount2, ...amount6
var amount1 = 125;
var amount2 = 75;
var amount3 = 50;
var amount4 = 150;
var amount5 = 250;
var amount6 = 50;
var totalAmount = amount1 + amount2 + amount3 + amount4 + amount5 + amount6;
var totalContributors = 6;
$("contributions").value = totalAmount.toFixed(2);
}
__
#title {
width: 600px;
text-align:right;
color: rgb(192,142,90);
border-bottom: 1px solid rgb(232,182,130);
margin-bottom:9px;
font-size:10pt;
height: 100px;
}
#title img {
float: left;
}
#data_list {
float: left;
}
table {
font-size: 8pt;
font-family: Arial, Helvetica, sans-serif;
border: 1px solid brown;
margin-right: 20px;
}
.yellowrow {
background-color: yellow;
}
th {
color: white;
background-color: brown;
padding: 2px 5px;
}
td {
vertical-align: top;
padding: 2px 5px;
}
.amt {
text-align: right;
}
#totals table {
font-size: 12pt;
border: solid black 1px;
}
#totals table th {
text-align: left;
}
#totals table td {
text-align: right;
width: 75px;
}
#totals table #sumTitle {
text-align: center;
background-color: yellow;
color: black;
}
In the below line:
$("contributions").value = totalAmount.toFixed(2);
You have forgot # as contributions is id of td so use this:
$("#contributions").html(totalAmount.toFixed(2));
And .value is the javascript and you are using jQuery so use .html function instead of .value .
And you have not added jquery library in your HTML page, add jquery library also.
And If your JS is in different file then add the file also in the code.
Use this:
<script type="text/javascript" src="your/file/path/*.js"></script>
$("contributions").value = totalAmount.toFixed(2);
this should probably be:
$("#contributions").html(totalAmount.toFixed(2));
So instead it does target the contributions td (based on id because of # just like in css).
And the html sets the innerHTML, you could just use text() instead if it's just plaintext.
2 issues I see:
1) you should be looking for $("#contributions") since you are querying by id.
2) since contributions is a td you should use its innerHTML property to set content, rather than value.

Categories

Resources