Populate HTML table from Javascript array - javascript

I would like to take data from a Javascript array and place it into an HTML table. A Javascript file, including arrays and basic functions, was provided. I want to put the array data into my HTML table by calling the functions. The following Javascript was given:
var subject = ['Call Your Mother', 'Cheap Online Meds', 'Change Your Life Today', 'Sppoky Stories', 'Meet Singles In Your Area', 'Have You Heard?', 'Yo', 'RE: Looking for a three legged cat', 'Get Rich Quick!', 'FW: Token Chain Email'];
var sender = ['Mary Monster', 'Dave Danger', 'Spam Master', 'Spike Spurner', 'Ray Ranger', 'Catherine Chaos', 'Van Pire', 'Andy Argye', 'Rick Roger', 'Sue Mee'];
var body = ['Message 1','Message 2','Message 3','Message 4','Message 5','Message 6','Message 7','Message 8','Message 9','Message 10'];
function loadGeeMails(){
for (var i = 0; i < 10; i++){
var message = generateMessage();
window.geemails.push(message);
}
}
function generateMessage(date){
var message = {};
message.date = date || getRandomDate();
message.subject = getRandomElement(subject);
message.sender = getRandomElement(sender);
message.body = getRandomElement(body);
return message;
}
function getRandomElement(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function getNewMessage(){
var now = new Date();
return generateMessage(now);
}
function getRandomDate(){
var year = 2013;
var month = Math.floor(Math.random() * 12) + 1;
var day = Math.floor(Math.random() * 30) + 1;
var hours = Math.floor(Math.random() * 12) + 1;
var minutes = Math.floor(Math.random() * 59) + 1;
return new Date(year, month, day, hours, minutes);
}
//load intial GeeMail data to window object
(function(){
window.geemails = [];
loadGeeMails();
})();
I want to use those arrays and/or functions to populate the HTML table below:
<html>
<head>
<Title>Kevin Gee-mail Challenge</title>
<script src="js/mail-generator.js"></script>
<link href="css/style.css" rel="stylesheet" media="screen">
<script>
window.onload = function(){
//Call javascript here
};
</script>
</head>
<body>
<div class="container" id="main"></div>
<h1>This is your inbox.</h1>
<table>
<tr>
<th>Date</th>
<th>Sender</th>
<th>Subject</th>
<th>Body</th>
</tr>
<tr>
<td class="date"></td>
<td class="sender"></td>
<td class="subject"></td>
<td class="body"></td>
</tr>
</table>
</body>
</html>

var subject = ['Call Your Mother', 'Cheap Online Meds', 'Change Your Life Today', 'Sppoky Stories', 'Meet Singles In Your Area', 'Have You Heard?', 'Yo', 'RE: Looking for a three legged cat', 'Get Rich Quick!', 'FW: Token Chain Email'];
var sender = ['Mary Monster', 'Dave Danger', 'Spam Master', 'Spike Spurner', 'Ray Ranger', 'Catherine Chaos', 'Van Pire', 'Andy Argye', 'Rick Roger', 'Sue Mee'];
var body = ['Message 1','Message 2','Message 3','Message 4','Message 5','Message 6','Message 7','Message 8','Message 9','Message 10'];
function loadGeeMails(){
for (var i = 0; i < 10; i++){
var message = generateMessage();
window.geemails.push(message);
}
}
function generateMessage(date){
var message = {};
message.date = (date || getRandomDate()).toDateString();
message.subject = getRandomElement(subject);
message.sender = getRandomElement(sender);
message.body = getRandomElement(body);
return message;
}
function getRandomElement(arr){
return arr[Math.floor(Math.random() * arr.length)];
}
function getNewMessage(){
var now = new Date();
return generateMessage(now);
}
function getRandomDate(){
var year = 2013;
var month = Math.floor(Math.random() * 12) + 1;
var day = Math.floor(Math.random() * 30) + 1;
var hours = Math.floor(Math.random() * 12) + 1;
var minutes = Math.floor(Math.random() * 59) + 1;
return new Date(year, month, day, hours, minutes);
}
$("document").ready(function(){
window.geemails = [];
loadGeeMails(); console.log(window.geemails);
$("#emailTemplate").tmpl(window.geemails).appendTo("#emailContainer");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<div class="container" id="main"></div>
<h1>This is your inbox.</h1>
<table>
<tr>
<th>Date</th>
<th>Sender</th>
<th>Subject</th>
<th>Body</th>
</tr>
<tbody id="emailContainer">
</tbody>
</table>
<!-- This is the template -->
<script id="emailTemplate" type="text/x-jquery-tmpl">
<tr>
<td> ${date} </td>
<td> ${sender} </td>
<td> ${subject} </td>
<td> ${body} </td>
</tr>
</script>
Here is the better way of doing it just use the JQuery template bindings and this could be real easy and clean.Please find the JSfiddle JSFiddle
JS Fiddle link http://jsfiddle.net/cc44s778/

Create a function that will iterate over window.geemails and create tr elements which will append to the table in question. For example :-
function createTableRows(){
for(var i=0; i < window.geemails.length; i++){
var obj = window.geemails[i];
var trElm = document.createElement('tr');
var dateTdElm = document.createElement('td');
var dateTxt = document.createTextNode(obj.date);
dateTdElm.appendChild(dateTxt);
var senderTdElm = document.createElement('td');
var senderTxt = document.createTextNode(obj.sender);
senderTdElm.appendChild(senderTxt);
var subjectTdElm = document.createElement('td');
var subjectTxt = document.createTextNode(obj.subject);
subjectTdElm.appendChild(subjectTxt);
var bodyTdElm = document.createElement('td');
var bodyTxt = document.createTextNode(obj.body);
bodyTdElm.appendChild(bodyTxt);
trElm.appendChild(dateTdElm);
trElm.appendChild(senderTdElm);
trElm.appendChild(subjectTdElm);
trElm.appendChild(bodyTdElm);
document.tables[0].appendChild(trElm);
}
}
However, I would suggest using datatables or a js library (if possible) for such requirements.
- good luck

Related

Multiple countdown timers comparing a given time and current time?

Really struggling with this part for some reason.
I'm creating a timer I can use to keep track of bids. I want to be able to compare two times and have the difference (in minutes and seconds) shown in the countdown column. It should be comparing the bid start time and the time right now.
Perhaps when it reaches bid start it could also change to show how long until bid ends. Eventually I want to add background changes once it's getting close to the time, and perhaps the ablility to set alarms with a prompt window.
Here's the code I have so far:
HTML
<table>
<tr>
<td>Item Name</td>
<td><input id="itemNameField" placeholder="" type="text"></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Time of Notice</td>
<td><input id="noticeField" type="time"></td>
</tr>
</table>
<input id="addButton" onclick="insRow()" type="button" value="Add Timer">
<div id="errorMessage"></div>
<hr>
<div id="marketTimerTableDiv">
<table border="1" id="marketTimerTable">
<tr>
<td></td>
<td>Item Name</td>
<td>Time of Notice</td>
<td>Bid Start</td>
<td>Bid End</td>
<td>Countdown</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<div id="itembox"></div>Example Item
</td>
<td>
<div id="noticebox"></div>12:52
</td>
<td>
<div id="bidstartbox"></div>13:02
</td>
<td>
<div id="bidendbox"></div>13:07
</td>
<td>
<div id="countdownbox"></div>
</td>
<td><input id="delbutton" onclick="deleteRow(this)" type="button" value="X"></td>
</tr>
</table>
</div>
JAVASCRIPT
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
if (i == 1) {
console.log = "hi";
} else {
document.getElementById('marketTimerTable').deleteRow(i);
}
}
function insRow() {
if (itemNameField.value == "" || noticeField.value == "") {
var div = document.getElementById('errorMessage');
div.innerHTML = "*Please fill in the fields*";
div.style.color = 'red';
document.body.appendChild(div);
} else {
var div = document.getElementById('errorMessage');
div.innerHTML = "";
var x = document.getElementById('marketTimerTable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var inp1 = new_row.cells[1].getElementsByTagName('div')[0];
inp1.id += len;
inp1.innerHTML = itemNameField.value;
itemNameField.value = "";
var inp2 = new_row.cells[2].getElementsByTagName('div')[0];
inp2.id += len;
inp2.innerHTML = noticeField.value;
noticeField.stepUp(10);
var inp3 = new_row.cells[3].getElementsByTagName('div')[0];
inp3.id += len;
inp3.innerHTML = noticeField.value;
noticeField.stepUp(5);
var inp4 = new_row.cells[4].getElementsByTagName('div')[0];
inp4.id += len;
inp4.innerHTML = noticeField.value;
var inp5 = new_row.cells[5].getElementsByTagName('div')[0];
inp5.id += len;
inp5.innerHTML = "";
noticeField.value = "";
x.appendChild(new_row);
}
}
I apologize in advance because my code is probably really messy and badly formatted. Here's a JSFIDDLE as well! Thanks :)
To calculate the difference between the current and given time, you can use setInterval
Example :
var noticeTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
var diffInHours = currentDate.getHours() - noticeTime[0];
var diffInMinutes = currentDate.getMinutes() - noticeTime[1];
inp5.innerHTML = diffInHours + ":" + diffInMinutes;
if(diffInHours === 0 && diffInMinutes === 0) {
clearInterval(interval);
}
},1000)
I managed to do it with the help of the code from ProgXx.
I added the following code:
var noticeTime = noticeField.value.split(":");
var originalTime = noticeField.value.split(":");
const interval = setInterval(function(){
var currentDate = (new Date());
noticeTime[1] = originalTime[1] - currentDate.getMinutes() + 10;
noticeTime[1] = noticeTime[1] + (originalTime[0] * 60) - (currentDate.getHours() * 60);
Here's a JSFIDDLE of the finihsed code: http://jsfiddle.net/joefj8wb/

Unable to populate my javascript data to HTML

Hi I unable to connect my javascript file to html. I tried coding everything and now I am unable to see changes in HTML. I am here trying to calculate the tax rate of employees with their overtime worked with tax deduction .
Thanks in advance. Please help.
My code for html is
<!doctype html>
<html>
<head>
<script language="JavaScript" src="employees.js"></script>
<link rel="stylesheet" type="text/css" href="employees.css" />
<title>Pay Form</title>
</head>
<body>
<section id="content">
<h1>
Employee Payroll Entry Form
</h1>
<div id="payForm">
<p>
<label for="fullName">Full Name:</label><input type="text" autofocus id="fullName" />
</p>
<p>
<label for="hoursWorked">Hours Worked:</label><input type="text" id="hoursWorked" />
</p>
<p>
<label for="hourlyRate">Hourly Rate:</label><input type="text" id="hourlyRate" />
</p>
<footer>
<button id="calculateButton" onclick="calculate()">Calculate</button>
</footer>
</div>
<h1>
Employee Payroll Summary Report
</h1>
<table id = "employees">
<tr>
<th>Employee Name</th>
<th>Gross Pay</th>
<th>Tax</th>
<th>Net Pay</th>
</tr>
</table>
</section>
</body>
and my javascript is
var fname = document.getElementById("fullName");
var hours = document.getElementById("hoursWorked");
var rate = document.getElementById("hourlyRate");
var table = document.getElementById("employees");
var gross;
var net;
var tax;
var overtime;
function grosspay() {
if (hours > 0 && hours < 40) {
gross = hours * rate;
} else if (hours < 40) {
overtime = hours - 40;
gross = (40 * rate) + (overtime * (rate * 1.5));
}
}
function taxPay() {
if (gross < 250) {
tax = gross * 0.25;
} else if (gross >= 250 && gross < 500) {
tax = gross * 0.30;
} else if (gross >= 500 && gross < 750) {
tax = gross * 0.40;
} else if (gross > 750) {
tax = gross * 0.50;
}
}
function netPay() {
net = gross - tax;
}
function calculate() {
if (hours > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
function load() {
var calculateButton = document.getElementById("calculateButtom");
calculateButton.addEventListener("click", calculate);
}
you are get the elements like "hours" but not its value.
Please try the following calculate function and if still got problem please post the debugger output so that others can help you.
function calculate() {
var hoursValue = hours.value;
console.log("Hours are : " + hoursValue );
if (hoursValue > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
you are get the elements but not its value.
get the values of input fields like:
var hours = document.getElementById("hoursWorked").value;
var rate = document.getElementById("hourlyRate").value;
and also move script tag to the bottom of the page inside body tag.

Javascript days in October

I have a funny bug in my calculation about interest days. I go through each day and check which day it is (1 to 31). Now I found a problem: In October the count doesn't work properly. That means the 27th is the 26th, or the 29th is the 28th. Is this a well know problem?
Maybe the problem is in my code, but, because it works over another period, it seems to be fine.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function berecheZinstage() {
//eingabe von den Feldern holen
var strVon = txtVonDatum.value;
var strBis = txtBisDatum.value;
//label um das Resultat anzuzeigen
var resultatTage = document.getElementById("lblTage");
var resultatZinsTage = document.getElementById("lblZinstage");
//tag als Milisekunden
var tagMs = 86400000;
var monatCount;
//Eingabeformat umwandeln für die Berechung
strVon = strVon.replace(/-/g, "/");
strBis = strBis.replace(/-/g, "/");
var vonDatum = new Date(strVon);
var bisDatum = new Date(strBis);
var zinsTage = 0;
if (bisDatum > vonDatum) {
var totTage = bisDatum - vonDatum;
var nDays = Math.round(totTage / (1000 * 60 * 60 * 24));
var pruefMS = vonDatum.getTime();
var startMS = vonDatum.getTime();
var endeMS = bisDatum.getTime();
var febCount = 0;
var langCount = 0;
var tage = 0;
for (var i = 0; i < nDays; i++) {
pruefMS = pruefMS + tagMs;
var pruefDatum = new Date(pruefMS);
var pruefMonat = pruefDatum.getMonth();
var pruefJahr = pruefDatum.getFullYear();
var pruefTag = pruefDatum.getDate();
if (pruefTag == 1 && pruefDatum != startMS) {
if (pruefMonat == 2) {
var istSchaltjahr = new Date(pruefJahr, 1, 29).getMonth() == 1;
if (istSchaltjahr) {
tage++;
}
else {
tage = tage + 2;
}
}
}
if (pruefTag != 31) {
tage++;
}
}
resultatZinsTage.innerText = tage.toString();
resultatTage.innerText = pruefTag;//nDays.toString();
}
else {
resultatTage.innerText = "Bis Datum muss grösser sein als von Datum";
}
}
</script>
<title>Zinstage berechen</title>
</head>
<body>
<table style="width:100%;">
<tr>
<td style="width:100px;"><input id="txtVonDatum" type="text" /></td>
<td style="width:100px;"><input id="txtBisDatum" type="text" /></td>
<td style="width:100px;"><button id="btnCalcDays" type="button" onclick="berecheZinstage();">Berechnen</button></td>
<td> </td>
</tr>
<tr>
<td>Tage:</td>
<td><label id="lblTage"></label></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Zinstage:</td>
<td><label id="lblZinstage"></label></td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Thanks, Marlowe
I don't understand what this code is trying to achieve, but the problem is DST (Daylight Saving Time).
Adding 86400000 millis for each day should work ok. But in locales that use DST (default in Germany), the result of date "2013/10/01 00:00:00" + 31*86400000 would be "2013/10/31 23:00:00".
Actually if we include the timezone, it would be "2013/10/01 00:00:00 GMT+0200" + 31*86400000 would be "2013/10/31 23:00:00 GMT+0100", so the addition is correct in UTC terms.
Likewise in March, the resulting date would be "2013/04/01 01:00:00", but we don't see the error since we're only counting the days.
When performing operations like this, always use UTC to avoid headaches :)
Here is now the working code. With the hint given by foibs I've built a little hack to calculate the interest days.
<script type="text/javascript">
function calcInterestDays() {
//get the values from the input fields
var strFrom = document.getElementById("txtFromDate").value;
var strTill = document.getElementById("txtTillDate").value;
//format strings
strFrom = strFrom.replace(/-/g, "/");
strTill = strTill.replace(/-/g, "/");
var fromDate = new Date(strFrom);
var tillDate = new Date(strTill);
var msDay = 86400000;
var startMS = fromDate.getTime();
var totDays = Math.round((tillDate - fromDate) / (1000 * 60 * 60 * 24));
var totMs = startMS;
var outputStr = "";
var days = 0;
for (var i = 0; i < totDays; i++) {
totMs = totMs + msDay;
var checkDate = new Date(totMs);
var splitDate = checkDate.toString().split(" ");
if (splitDate[6] == "0200") {
var calcDay = new Date(totMs);
}
else {
var calcDay = new Date(totMs + 3600000);
}
if (calcDay.getDate() == 1 && totMs != startMS) {
if (calcDay.getMonth() == 2) {
var istSchaltjahr = new Date(calcDay.getFullYear(), 1, 29).getMonth() == 1;
if (istSchaltjahr) {
days++;
}
else {
days = days + 2;
}
}
}
if (calcDay.getDate() != 31) {
days++;
}
outputStr = outputStr + "<br>" + calcDay;
}
document.getElementById("lblTotDays").innerHTML = totDays;
document.getElementById("lblInterestDays").innerHTML = days;
document.getElementById("output").innerHTML = outputStr;
}
</script>
Thanks for all the help.

Updating row ID when swapping HTML table rows

I've been messing with manipulating HTML tables for the past few weeks and I've come across a problem I am not sure how to fix. So the collection of rows for a table can be iterated over like an array, but if you've switched out the rows a lot, won't the IDs be mixed and doesn't the browser rely on the IDs as the way to iterate over the row objects? I'm running into a problem (probably due to a lack of understanding) where the rows eventually stop moving or one row gets duplicated on top of another. Should I somehow be updating the row's ID each time it is moved? Here is my source so far for this function.
function swap(rOne, rTwo, tblID) {
tblID.rows[rOne].setAttribute('style', 'background-color:#FFFFFF');
var tBody = tblID.children[0];
var rowOne;
var rowTwo;
if (rOne > rTwo) {
rowOne = rOne;
rowTwo = rTwo;
}
else {
rowOne = rTwo;
rowTwo = rOne;
}
var swapTempOne = tblID.rows[rowOne].cloneNode(true);
var swapTempTwo = tblID.rows[rowTwo].cloneNode(true);
hiddenTable.appendChild(swapTempOne);
hiddenTable.appendChild(swapTempTwo);
tblID.deleteRow(rowOne);
var rowOneInsert = tblID.insertRow(rowOne);
var rowOneCellZero = rowOneInsert.insertCell(0);
var rowOneCellOne = rowOneInsert.insertCell(1);
var rowOneCellTwo = rowOneInsert.insertCell(2);
var rowOneCellThree = rowOneInsert.insertCell(3);
rowOneCellZero.innerHTML = hiddenTable.rows[2].cells[0].innerHTML;
rowOneCellOne.innerHTML = hiddenTable.rows[2].cells[1].innerHTML;
rowOneCellTwo.innerHTML = hiddenTable.rows[2].cells[2].innerHTML;
rowOneCellThree.innerHTML = hiddenTable.rows[2].cells[3].innerHTML;
tblID.deleteRow(rowTwo);
var rowTwoInsert = tblID.insertRow(rowTwo);
var rowTwoCellZero = rowTwoInsert.insertCell(0);
var rowTwoCellOne = rowTwoInsert.insertCell(1);
var rowTwoCellTwo = rowTwoInsert.insertCell(2);
var rowTwoCellThree = rowTwoInsert.insertCell(3);
rowTwoCellZero.innerHTML = hiddenTable.rows[1].cells[0].innerHTML;
rowTwoCellOne.innerHTML = hiddenTable.rows[1].cells[1].innerHTML;
rowTwoCellTwo.innerHTML = hiddenTable.rows[1].cells[2].innerHTML;
rowTwoCellThree.innerHTML = hiddenTable.rows[1].cells[3].innerHTML;
tblID.rows[rowOne].setAttribute('onclick', 'chkThis(event, this)');
tblID.rows[rowTwo].setAttribute('onclick', 'chkThis(event, this)');
for (iHiddenDelete = 2; iHiddenDelete >= 1; iHiddenDelete--) {
hiddenTable.deleteRow(iHiddenDelete);
}
}
EDIT: Adding HTML for page and the function for moving between tables which I suspect is causing the issue.
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
FUNCTION STARTS HERE
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var cln = row.cloneNode(true);
toTbl.appendChild(cln);
frTbl.deleteRow(num);
}
sum();
}
So it turns out that my row cloning for moving between tables was causing malformed HTML where the rows would not longer be inside the table body tags. In addition, not trusting the browser to keep track of the button IDs and using the button IDs to setAttributes to the button also caused button ID overlap eventually. So, I got rid of the node cloning and did the row moving between tables the manual way and used innerHTML to add the function call inside the buttons. Upon further reflection, I've come to learn that some people actually make functions that handle ALL button clicks without calling them inside the button and route them to the proper function depending on the ID or other factors such as parent nodes of the button. Perhaps that is best. The main trick here is to STICK TO ONE METHOD. I was all over the place in how I manipulated the tables and it broke things. Here is the working source for those looking to do similar things.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
table, th, td
{
border: 1px solid black;
}
</style>
<title>Loader</title>
<script>
var chkArray = [];
var data = [];
var tmpArray = [];
var iChk = 0;
var swap;
window.onload = function () {
var load = document.getElementById('selectSource')
loadFromAJAX();
}
function loadFromAJAX()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var rawData = xmlhttp.responseText;
data = JSON.parse(rawData);
for (iData = 0; iData < data.length; iData++) {
newRow = document.getElementById('tblSource').insertRow(iData + 1);
var dn = "dn" + (iData + 1);
var up = "up" + (iData + 1);
cel0 = newRow.insertCell(0);
cel1 = newRow.insertCell(1);
cel2 = newRow.insertCell(2);
cel3 = newRow.insertCell(3);
cel4 = newRow.insertCell(4);
cel0.innerHTML = "<input type='checkbox' name='chkbox'>";
cel1.innerHTML = data[iData].num;
cel2.innerHTML = data[iData].cube;
cel3.innerHTML = data[iData].wgt;
cel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
}
}
}
xmlhttp.open("POST","http://192.168.3.2/cgi-bin/rims50.cgi/json.p",true);
xmlhttp.send();
}
function moveUp(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowIndex = mvThisRowRow.rowIndex;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex - 1;
var mvThisDn = "dn" + (mvToRow) + mvThisRowTbl;
var mvThisUp = "up" + (mvToRow) + mvThisRowTbl;
if (mvThisRowIndex - 1 !== 0) {
moveToRow = mvThisRowTbl.insertRow(mvToRow);
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex +1);
}
else {
alert("You can't move the top row 'up' try moving it 'down'.");
}
}
function moveDn(mvThisRow) {
var mvThisRowRow = mvThisRow.parentNode.parentNode;
var mvThisRowTbl = mvThisRowRow.parentNode.parentNode;
var mvThisRowTblLngth = mvThisRowTbl.rows.length;
var mvThisRowIndex = mvThisRowRow.rowIndex;
if (mvThisRowIndex + 1 !== mvThisRowTblLngth) {
var mvFrRow = mvThisRowTbl.rows[mvThisRowIndex];
var mvToRow = mvThisRowIndex + 2;
var moveToRow = mvThisRowTbl.insertRow(mvToRow);
var dn = "dn" + (mvToRow) + mvThisRowTbl;
var up = "up" + (mvToRow) + mvThisRowTbl;
mvRowCel0 = moveToRow.insertCell(0);
mvRowCel1 = moveToRow.insertCell(1);
mvRowCel2 = moveToRow.insertCell(2);
mvRowCel3 = moveToRow.insertCell(3);
mvRowCel4 = moveToRow.insertCell(4);
mvRowCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvRowCel1.innerHTML = mvFrRow.cells[1].innerHTML;
mvRowCel2.innerHTML = mvFrRow.cells[2].innerHTML;
mvRowCel3.innerHTML = mvFrRow.cells[3].innerHTML;
mvRowCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
mvThisRowTbl.deleteRow(mvThisRowIndex);
}
else {
alert("You can't move the bottom row 'down' try moving it 'up'.");
}
}
function sum() {
var trgTbl = document.getElementById('tblTarget');
var tblLength = trgTbl.rows.length;
var sumAddCube = 0;
var sumAddWgt = 0;
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
for (iSum = 1; iSum < tblLength; iSum++) {
celCubeNum = trgTbl.rows[iSum].cells[2].innerHTML;
celWgtNum = trgTbl.rows[iSum].cells[3].innerHTML;
sumAddCube = parseInt(sumAddCube) + parseInt(celCubeNum);
sumAddWgt = parseInt(sumAddWgt) + parseInt(celWgtNum);
}
document.getElementById("cubesum").setAttribute("value", sumAddCube);
document.getElementById("wgtsum").setAttribute("value", sumAddWgt);
}
function move(from, to) {
var frTbl = document.getElementById(from);
var toTbl = document.getElementById(to);
chkArray.length = 0;
cbsMove = frTbl.getElementsByTagName('input');
for (var oChk = 0; oChk < cbsMove.length; oChk++) {
if (cbsMove[oChk].type == 'checkbox') {
if (cbsMove[oChk].checked == true) {
var prntRow = cbsMove[oChk].parentNode.parentNode;
var prntRowIdx = prntRow.rowIndex;
chkArray.push(prntRowIdx);
cbsMove[oChk].checked = false;
}
}
}
for (iMove = chkArray.length -1; iMove >= 0; iMove--) {
var num = chkArray[iMove];
var row = frTbl.rows[num];
var toRow = toTbl.rows.length
moveRow = toTbl.insertRow(toRow);
var dn = "dn" + (toRow) + toTbl;
var up = "up" + (toRow) + toTbl;
mvCel0 = moveRow.insertCell(0);
mvCel1 = moveRow.insertCell(1);
mvCel2 = moveRow.insertCell(2);
mvCel3 = moveRow.insertCell(3);
mvCel4 = moveRow.insertCell(4);
mvCel0.innerHTML = "<input type='checkbox' name='chkbox'>";
mvCel1.innerHTML = row.cells[1].innerHTML;
mvCel2.innerHTML = row.cells[2].innerHTML;
mvCel3.innerHTML = row.cells[3].innerHTML;
mvCel4.innerHTML = "<button type='button' onclick=moveUp(this)>up</button><button type='button' onclick=moveDn(this)>down</button>";
frTbl.deleteRow(num);
}
sum();
}
</script>
</head>
<body>
<form>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
<form>
<table id="tblSource">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="move('tblSource','tblTarget')" style="width: 58px">To Trucks (Down)</button>
<button type="button" onclick="move('tblTarget', 'tblSource')" style="width: 58px">To Orders (Up)</button>
</form>
<form>
<table id="tblTarget">
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<table id="hiddenTable" style="display: none"> <!--this table is hidden! -->
<thead>
<tr>
<th> </th>
<th>Order</th>
<th>Cube</th>
<th>Weight</th>
<th>Move</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

Trying to have both stylize() randomly select cell bgcolor and text style separately using CSS style

Here is the code. The random font styles work but I can't get the random background color to work. I see there was a post a while back almost exactly like this on but I'm too new to understand how to use their answer to fix mine. previous post
<html>
<head>
<title>HTML and JavaScript</title>
<link href="js-twentyfive.css" rel="stylesheet" type="text/css"></link>
<script>
var index = 0;
function stylize()
{
if (index > 20) index = 1;
var s = "myStyle" + index;
var e = document.getElementById("MessageText")
e.className = s
{
var bgindex = 0;
bgindex++;
if (bgindex >5) bgindex =1;
var b ="myBackground" + bgindex;
var c = document.getElementById("MessageCell")
c.className = b
}
}
function getRandomInt (min, max)
{
return Math.floor(Math.random() *(max - min +1)) + min;
}
index = getRandomInt(1, 20);
bgindex = getRandomInt(1, 5);
</script>
</head>
<body onLoad="stylize()">
<table align="center" border="1" bordercolor="black">
<tr>
<td align="center">
<font size="3"><b>STYLE CLASS VIEWER</b></font>
</td>
</tr>
<tr>
<td id="MessageCell" align="center" height="100" width="400">
<div id="MessageText">
Hello World Wide Web!
</div>
</td>
</tr>
</table>
</body>
<html>
Here is my CSS:
.myBackground1{color:blue}
.myBackground2{color:red}
.myBackground3{color:purple}
.myBackground4{color:yellow}
.myBackground5{color:orange}
.myStyle1 {color:black; font-size:12}
.myStyle2 {color:red; font-family:Lucida Grande;font-size:14}
.myStyle3 {color:blue; font-family:serif;font-size:16}
.myStyle4 {color:green; font-family:times; font-size:18}
.myStyle5 {color:yellow; font-family:monospace; font-size:22}
.myStyle6 {color:orange; font-family:"Brush Script MT", cursive;font-size:12}
.myStyle7 {color:cyan; font-size:14}
.myStyle8 {color:purple; font-size:16}
.myStyle9 {color:pink; font-size:18}
.myStyle10 {color:lightred; font-size:22}
.myStyle11 {color:lightblue; font-size:12}
.myStyle12 {color:White Orchid; font-size:16}
.myStyle13 {color:deepskyblue4; font-family:Copperplate; font-size:14}
.myStyle14 {color:firebrick; font-size:18}
.myStyle15 {color:green4; font-size:12}
.myStyle16 {color:lightcoral; font-size:14}
.myStyle17 {color:black; font-size:16}
.myStyle18 {color:black; font-family: Papyrus, fantasy; font-size:18}
.myStyle19 {color:magenta; font-size:14}
.myStyle20 {color:black; font-size:16};
If I understood correctly, you are not being able to change the background correct? You need to fix the following CSS styles:
.myBackground1{color:blue}
.myBackground2{color:red}
etc...
with
.myBackground1{background-color:blue}
.myBackground2{background-color:red}
etc...
and change the code:
function stylize()
{
if (index > 20) index = 1;
var s = "myStyle" + index;
var e = document.getElementById("MessageText")
e.className = s
{
var bgindex = 0;
bgindex++;
if (bgindex >5) bgindex =1;
var b ="myBackground" + bgindex;
var c = document.getElementById("MessageCell")
c.className = b
}
}
with
function stylize()
{
index = getRandomInt(1, 20);
var s = "myStyle" + index;
var e = document.getElementById("MessageText")
e.className = s
bgindex = getRandomInt(1, 5);
var b ="myBackground" + bgindex;
var c = document.getElementById("MessageCell")
c.className = b
alert(b);
}
Your function was not taking into consideration the random value from 1-5 from bgIndex. It was always setting it up to 1, so after fixing the CSS, you would always have a blue background

Categories

Resources