My output is not displaying - javascript

So in HTML file I am taking in 6 numbers which will be used to determine the derivative for a user input amount of time. And this is the code that I have for the HTML
<body>
<h1>Enter your numbers:</h1>
<table>
<tr>
<h4>Enter your first number:</h4><input type="text" name="firstNum" id="first">
<h4>Enter your second number:</h4><input type="text" name="secondNum" id="second">
<h4>Enter your third number:</h4><input type="text" name="thirdNum" id="third">
<h4>Enter your fourth number:</h4><input type="text" name="fourthNum" id "fourth">
<h4>Enter your fifth number:</h4><input type="text" name="fifthNum" id="fifth">
<h4>Enter your sixth number:</h4><input type="text" name="sixthNum" id="sixth">
<h4>Enter the number of rows:</h4><input type="text" name="rowsNum" id="rows">
</tr>
</table>
<table style="width:100%">
<tr>
<th>y</th>
<th>&#9651y</th>
<th>&#9651<sup>2</sup>y</th>
<th>&#9651<sup>3</sup>y</th>
<th>&#9651<sup>4</sup>y</th>
</tr>
</table>
<button type="button" onclick="submitForCalc()">Submit</button>
<div id="tablePrint"> </div>
<script src="babbCore.js"> </script>
</body>
And in my js file I have
function submitForCalc()
{
/*
If no inputs are given the defaults will be 0
*/
var firstInput = 0;
var secondInput =0;
var thirdInput =0;
var fourthInput =0;
var fifthInput =0;
var sixthInput =0;
var rowInput = 1;
/*
Stores the user inputs into the values
*/
firstInput = document.getElementById("first").value;
secondInput = document.getElementById("second").value;
thirdInput = document.getElementById("third").value;
fourthInput = document.getElementById("fourth").value;
fifthInput = document.getElementById("fifth").value;
sixthInput = document.getElementById("sixth").value;
rowInput = document.getElementById("rows").value;
/*
stores the answer for each derivative into an array
*/
var zeroDir = new Array();
var firstDir = new Array();
var secondDir = new Array();
var thirdDir = new Array();
var fourthDir = new Array();
var fifthDir = new Array();
var myTable = "<table style="width:100%><tr>"; //the table of outputs
//This is where the calculations are done
var i =0;
for (i; i<rowInput; i++)
{
zeroDir[i] = (firstInput*Math.pow(i, 5))+(secondInput*Math.pow(i, 4))+(thirdInput*Math.pow(i, 3))+(fourthInput*Math.pow(i, 2))+(fifthInput*Math.pow(i, 1))+sixthInput;
firstDir[i] = ((5*firstInput)*Math.pow(i, 4))+((4*secondInput)*Math.pow(i, 3))+((3*thirdInput)*Math.pow(i, 2))+((2*fourthInput)*Math.pow(i, 1))+fifthInput;
secondDir[i] = ((20*firstInput)*Math.pow(i, 3))+((12*secondInput)*Math.pow(i, 2))+((6*thirdInput)*Math.pow(i, 1))+(2*fourthInput);
thirdDir[i] = ((60*firstInput)*Math.pow(i, 2))+((24*secondInput)*Math.pow(i, 1))+(6*thirdInput);
fourthDir[i] = ((120*firstInput)*Math.pow(i, 1))+(24*secondInput);
fifthDir[i] = (120*firstInput);
}
//This is where the output is created
for (var j=0; j<i; j++)
{
myTable += "<th>"+zeroDir[j] + "</th>"+ "<th>"+firstDir[j] +"</th>"+ "<th>"+secondDir[j] + "</th>"+ "<th>"+thirdDir[j] + "</th>"+ "<th>" + fourthDir[j] + "</th>" + "<th>" +fifthDir[j]+ "</th>";
}
myTable+="</tr></table>";
document.getElementById('tablePrint').innerHTML = myTable;
}
I have everything set. When the user enters all the numbers the first to the fifth derivative will be calculated and stored into an array. After all the calculations are done it will then insert all the outputs into a table where it will be displayed in a table format. I used an alert to test weather or not my function was being called, and it was not. Any help would be appreciated.

Few things here
Never mix your markup with javascript
Try binding events at javascript end
Dont write strings as "".Make use of createElement and insertRows
Break down your code into multiple methods/subroutines it is diffilcut to understand if it takes more than 10 lines
window.onload = function() {
var submit = document.getElementById('submit');
submit.addEventListener('click', submitForCalc);
}
function submitForCalc() {
var firstInput = 0;
var secondInput = 0;
var thirdInput = 0;
var fourthInput = 0;
var fifthInput = 0;
var sixthInput = 0;
var rowInput = 1;
firstInput = document.getElementById("first").value;
secondInput = document.getElementById("second").value;
thirdInput = document.getElementById("third").value;
var fourthInput = document.getElementById("fourth").value;
fifthInput = document.getElementById("fifth").value;
sixthInput = document.getElementById("sixth").value;
rowInput = document.getElementById("rows").value;
/*
stores the answer for each derivative into an array
*/
var zeroDir = new Array();
var firstDir = new Array();
var secondDir = new Array();
var thirdDir = new Array();
var fourthDir = new Array();
var fifthDir = new Array();
var myTable = document.createElement('table');
myTable.style.width = "100%";
myTable.style.border = "1";
var i = 0;
for (var i = 0; i < rowInput; i++) {
zeroDir[i] = (firstInput * Math.pow(i, 5)) + (secondInput * Math.pow(i, 4)) + (thirdInput * Math.pow(i, 3)) + (fourthInput * Math.pow(i, 2)) + (fifthInput * Math.pow(i, 1)) + sixthInput;
firstDir[i] = ((5 * firstInput) * Math.pow(i, 4)) + ((4 * secondInput) * Math.pow(i, 3)) + ((3 * thirdInput) * Math.pow(i, 2)) + ((2 * fourthInput) * Math.pow(i, 1)) + fifthInput;
secondDir[i] = ((20 * firstInput) * Math.pow(i, 3)) + ((12 * secondInput) * Math.pow(i, 2)) + ((6 * thirdInput) * Math.pow(i, 1)) + (2 * fourthInput);
thirdDir[i] = ((60 * firstInput) * Math.pow(i, 2)) + ((24 * secondInput) * Math.pow(i, 1)) + (6 * thirdInput);
fourthDir[i] = ((120 * firstInput) * Math.pow(i, 1)) + (24 * secondInput);
fifthDir[i] = (120 * firstInput);
}
var header = myTable.createTHead();
var row = header.insertRow(0);
//This is where the output is created
for (var j = 0; j < i; j++) {
var thElement_1 = document.createElement('th');
thElement_1.innerHTML = zeroDir[j];
row.appendChild(thElement_1);
var thElement_2 = document.createElement('th');
thElement_2.innerHTML = firstDir[j];
row.appendChild(thElement_2);
var thElement_3 = document.createElement('th');
thElement_3.innerHTML = secondDir[j];
row.appendChild(thElement_3);
var thElement_4 = document.createElement('th');
thElement_4.innerHTML = thirdDir[j];
row.appendChild(thElement_4);
var thElement_5 = document.createElement('th');
thElement_5.innerHTML = fourthDir[j];
row.appendChild(thElement_5);
}
var printTable = document.getElementById('tablePrint');
printTable.append(myTable);
}
<h1>Enter your numbers:</h1>
<table>
<tr>
<h4>Enter your first number:</h4>
<input type="text" name="firstNum" id="first">
<h4>Enter your second number:</h4>
<input type="text" name="secondNum" id="second">
<h4>Enter your third number:</h4>
<input type="text" name="thirdNum" id="third">
<h4>Enter your fourth number:</h4>
<input type="text" name="fourthNum" id="fourth">
<h4>Enter your fifth number:</h4>
<input type="text" name="fifthNum" id="fifth">
<h4>Enter your sixth number:</h4>
<input type="text" name="sixthNum" id="sixth">
<h4>Enter the number of rows:</h4>
<input type="text" name="rowsNum" id="rows">
</tr>
</table>
<table style="width:100%">
<tr>
<th>y</th>
<th>&#9651y</th>
<th>&#9651<sup>2</sup>y</th>
<th>&#9651<sup>3</sup>y</th>
<th>&#9651<sup>4</sup>y</th>
</tr>
</table>
<button type="button" id="submit" >Submit</button>
<div id="tablePrint"></div>
Hope this helps

The primary change is, as wrote in a comment in the question, to change the definition of the table variable
var myTable = "<table style='width:100%'><tr>";
Coding on snippet i also had to change another line, but i was not able to find it again looking at the question, so i guess it was a problem with copy/paste.
Than it was everything working itself.
Sorry for delay adding details, but i was not here.
edit 2
The second problem was the definition in the html of <input type="text" name="fourthNum" id "fourth">. It was missing the =, so that i placed
The error got before this change was "trying to get property value of null", since off course it was impossible to find an element with id fourth before the edit.
function submitForCalc() {
/*
If no inputs are given the defaults will be 0
*/
var firstInput = 0;
var secondInput = 0;
var thirdInput = 0;
var fourthInput = 0;
var fifthInput = 0;
var sixthInput = 0;
var rowInput = 1;
/*
Stores the user inputs into the values
*/
firstInput = document.getElementById("first").value;
secondInput = document.getElementById("second").value;
thirdInput = document.getElementById("third").value;
fourthInput = document.getElementById("fourth").value;
fifthInput = document.getElementById("fifth").value;
sixthInput = document.getElementById("sixth").value;
rowInput = document.getElementById("rows").value;
/*
stores the answer for each derivative into an array
*/
var zeroDir = new Array();
var firstDir = new Array();
var secondDir = new Array();
var thirdDir = new Array();
var fourthDir = new Array();
var fifthDir = new Array();
var myTable = "<table style='width:100%'><tr>"; //the table of outputs
//This is where the calculations are done
var i = 0;
for (i; i < rowInput; i++) {
zeroDir[i] = (firstInput * Math.pow(i, 5)) + (secondInput * Math.pow(i, 4)) + (thirdInput * Math.pow(i, 3)) + (fourthInput * Math.pow(i, 2)) + (fifthInput * Math.pow(i, 1)) + sixthInput;
firstDir[i] = ((5 * firstInput) * Math.pow(i, 4)) + ((4 * secondInput) * Math.pow(i, 3)) + ((3 * thirdInput) * Math.pow(i, 2)) + ((2 * fourthInput) * Math.pow(i, 1)) + fifthInput;
secondDir[i] = ((20 * firstInput) * Math.pow(i, 3)) + ((12 * secondInput) * Math.pow(i, 2)) + ((6 * thirdInput) * Math.pow(i, 1)) + (2 * fourthInput);
thirdDir[i] = ((60 * firstInput) * Math.pow(i, 2)) + ((24 * secondInput) * Math.pow(i, 1)) + (6 * thirdInput);
fourthDir[i] = ((120 * firstInput) * Math.pow(i, 1)) + (24 * secondInput);
fifthDir[i] = (120 * firstInput);
}
//This is where the output is created
for (var j = 0; j < i; j++) {
myTable += "<th>" + zeroDir[j] + "</th>" + "<th>" + firstDir[j] + "</th>" + "<th>" + secondDir[j] + "</th>" + "<th>" + thirdDir[j] + "</th>" + "<th>" + fourthDir[j] + "</th>" + "<th>" + fifthDir[j] + "</th>";
}
myTable += "</tr></table>";
document.getElementById('tablePrint').innerHTML = myTable;
}
<body>
<h1>Enter your numbers:</h1>
<table>
<tr>
<h4>Enter your first number:</h4>
<input type="text" name="firstNum" id="first">
<h4>Enter your second number:</h4>
<input type="text" name="secondNum" id="second">
<h4>Enter your third number:</h4>
<input type="text" name="thirdNum" id="third">
<h4>Enter your fourth number:</h4>
<input type="text" name="fourthNum" id="fourth">
<h4>Enter your fifth number:</h4>
<input type="text" name="fifthNum" id="fifth">
<h4>Enter your sixth number:</h4>
<input type="text" name="sixthNum" id="sixth">
<h4>Enter the number of rows:</h4>
<input type="text" name="rowsNum" id="rows">
</tr>
</table>
<table style="width:100%">
<tr>
<th>y</th>
<th>&#9651y</th>
<th>&#9651<sup>2</sup>y</th>
<th>&#9651<sup>3</sup>y</th>
<th>&#9651<sup>4</sup>y</th>
</tr>
</table>
<button type="button" onclick="submitForCalc()">Submit</button>
<div id="tablePrint"></div>
<script src="babbCore.js">
</script>
</body>

Related

Get all spreadsheet data to client side first, then "find row number and same row values using javascript for a specific value"

Code.js
/**
* Load Spreadsheet by ID
* Get all Sheets present in that spreadsheet
* Loop through each sheet
* Create an object with sheet's name as Key of the object
* and sheets data as Value of the object
* Return the key-value paired object
*/
function doGet(e) {
return HtmlService
.createHtmlOutputFromFile('form.html')
.setTitle("Exam Result");
}
function getAllResult()
{
var id = '1da6d8rfWgZrG2Cnpyho6YDx0C7Me4o20rM4PhDi8yCY'; // ID of the Result spreadsheet
var ss = SpreadsheetApp.openById(id);
var sheets = ss.getSheets(); // get all the sheets in the spreadsheeet
var allSheetsData = {}; // initialize javascript object
var sheetName = '';
var sheetValues;
for (i = 0; i < sheets.length; i++) {
sheetName = sheets[i].getName();
sheetValues = sheets[i].getDataRange().getValues();
allSheetsData[sheetName] = sheetValues;
}
//Logger.log(allSheetsData);
return allSheetsData;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
init(); // initial function to run on page load
};
// initializing object that will be storing all result data
var allResultData = {};
// loading image
var loading = '<img width="25px" ' +
'src="https://lh6.googleusercontent.com/PshQKOjKS5j6IEaEXZ6r7-JOFZwYOBopBt82Q-kTGdRcW6wi3SBHDAUHebb2yreOeTpGfzgs=w1280-h661"> ' +
'Loading...';
/**
* First function to run on page load
*/
function init() {
document.getElementById('progressClass').innerHTML = loading; // show loading image
/**
* This calls getAllResult() function of Code.gs
* The returned value from getAllResult() is passed to populateClass(value) function
* present in this html file
*/
google.script.run
.withSuccessHandler(populateClass)
.getAllResult();
}
/**
* Second function to run after init() function
* Populates the "Class" select box
*/
function populateClass(value) {
document.getElementById('progressClass').innerHTML = ''; // hide loading image
allResultData = value; // all result data is stored in allResultData object
var className = Object.keys(value);
var classes = '<option>Please Select</option>';
for (i = 0; i < className.length; i++) {
classes += "<option>" + className[i] + "</option>";
}
document.getElementById("class").innerHTML = classes;
}
function populateSymbolNumber(value)
{
{var day = "<option>Day</option>";
var data = allResultData[value]
for (i=1; i < 32; i++) { // start from i=1, skipping 1st row as it's heading
day += "<option value="+i+">" + data[i][3] + "</option>";
}
document.getElementById("day").innerHTML = day;}
{var month = "<option>Month</option>";
var data = allResultData[value]
for (i=1; i < 13; i++) { // start from i=1, skipping 1st row as it's heading
month += "<option value="+i+">" + data[i][4] + "</option>";
}
document.getElementById("month").innerHTML = month;}
{var year = "<option>Year</option>";
var data = allResultData[value]
for (i=1; i < 122; i++) { // start from i=1, skipping 1st row as it's heading
year += "<option value="+i+">" + data[i][5] + "</option>";
}
document.getElementById("year").innerHTML = year;}
{var symbol = "<option>Please Select</option>";
var data = allResultData[value]
for (i=1; i < data.length; i++) { // start from i=1, skipping 1st row as it's heading
symbol += "<option value="+i+">" + data[i][0] + "</option>";
}
document.getElementById("symbol").innerHTML = symbol;}
}
/**
* Show name of student and marks result
*/
function submitForm(value) {
var grade = document.getElementById("class");
var gradeValue = grade.options[grade.selectedIndex].value;
var classResult = allResultData[gradeValue];
var symbol = document.getElementById("symbol");
var day = document.getElementById("day");
var month = document.getElementById("month");
var year = document.getElementById("year");
var symbolText = symbol.options[symbol.selectedIndex].text;
var DayText = day.options[day.selectedIndex].text;
var MonthText = month.options[month.selectedIndex].text;
var YearText = year.options[year.selectedIndex].text;
var symbolValue = symbol.options[symbol.selectedIndex].value;
var dob = DayText + '-' + MonthText + '-' + YearText;
var marks = '';
var headerRow = classResult[0];
//console.log(headerRow);
for (i = 1; i < headerRow.length; i++) { // start from i=1, skipping 1st column as it contains symbol number
marks += headerRow[i] + ': ' + classResult[symbolValue][i] + '<br>';
}
var result = "Symbol Number: " + symbolText + '<br>' + marks;
document.getElementById('result').innerHTML = result;
return false;
}
</script>
</head>
<body>
<div id="form">
<table cellpadding="5px">
<tr>
<td>Class</td>
<td>
<select id="class" onchange="populateSymbolNumber(this.value)">
<option value="">Please Select</option>
</select>
<span id="progressClass"></span>
</td>
</tr>
<tr>
<td>Symbol</td>
<td>
<select id="day">
<option value="">Day</option>
</select>
</td>
<td>
<select id="month">
<option value="">Month</option>
</select>
</td>
<td>
<select id="year">
<option value="">Year</option>
</select>
</td>
<td>
<select id="symbol">
<option value="">Please Select</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<button onclick="submitForm(); return false;">Submit</button>
</td>
</tr>
</table>
</div>
<div id="result" style="border-top: 1px solid #ccc; padding: 5px"></div>
</body>
</html>
There is a variable
var dob = DayText + '-' + MonthText + '-' + YearText;
I want to find row number for the "dob" value in the loaded data.
Google sheet has value as 30-December-1992.

I am trying to calculate the subtotal of a set of functions but am getting no output:

My html looks like this:
<tr>
<td><input id="z1" type="number"
oninput="calculateSubTotal()">
</td>
<td>Shirts - WASH - Qty 1 to 4</td>
<td>2.50 ea</td>
<td></td>
</tr>
and my js looks like this:
function calculateSubTotal() {
var subTotal = (getTableOnePrice() + getTableTwoPrice() + getTableThreePrice() + getTableFourPrice());
document.getElementById("subtotal").innerHTML = subTotal.toFixed(2);
return subTotal;
}
One of the functions looks like this:
function getTableTwoPrice(){
var ba = document.getElementById("y1").value * 6.00;
var bb = document.getElementById("y2").value * 1.25;
var bc = document.getElementById("y3").value * 4.00;
var bd = document.getElementById("y4").value * 6.00;
var be = document.getElementById("y5").value * 7.00;
var bf = document.getElementById("y6").value * 8.00;
var bg = document.getElementById("y7").value * 9.00;
var bh = document.getElementById("y8").value * 5.00;
var bi = document.getElementById("y9").value * 13.00;
var bj = document.getElementById("y10").value * 10.00;
var bk = document.getElementById("y11").value * 12.00;
var bl = document.getElementById("y12").value * 14.00;
var bm = document.getElementById("y13").value * 16.00;
var bn = document.getElementById("y14").value * 10.00;
var tableTwoTotal = ba + bb + bc + bd + be + bf + bg + bh + bi + bj + bk + bl + bm + bn;
return tableTwoTotal;
}
Try the onchage event. I've seen that oninput doesn't work in some cases.
I would focus on getting something to write to the screen first. And yes onchange is what you want here as oninput changes for every keystroke.
<tr>
<td><input id="z1" type="number" onchange="calculateSubTotal()">
</td>
<td>Shirts - WASH - Qty 1 to 4</td>
<td>2.50 ea</td>
<td></td>
</tr>
<div id='subtotal'></div>
<script>
function calculateSubTotal() {
var subTotal = getTableOnePrice();
document.getElementById("subtotal").innerHTML = subTotal.toFixed(2);
return subTotal;
}
function getTableOnePrice(){
return 5
}
</script>
once you have something like that working you can add the real getTableOnePrice() and all the others back in.

How to create random strings JS

The code below create 10 random strings, the idea is to have each string in a 'li'. With what I have, I able to create 10 random 'li', but after the sencond 'li' its a new string but with previous one. Is there a way to fix this?
Ex: This is what I trying to get
String 1
String 2
String 3
.......
The output that im currently getting is
String 1
String 1String 2
String 1String 2String 3
.....
Demo: https://jsfiddle.net/73cmb11q/
function names()
{
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
console.log(randomLength);
for(var j=0; j<10; j++)
{
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
for(var i=0; i<randomLength; i++)
{
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname+1);
}
var divName = document.getElementById('names');
divName.innerHTML += '<li>' + randomName + '</li>';
}
}
<form name="randomform">
<input type="button" value="Create" onClick="names()">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>
you can reset the string to "" each time after you append an li, so a new string is formed next time and you need to use += while adding innerHTML to your div otherwise you will have only one list as you keep replacing the previous ones.
function names()
{
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
console.log(randomLength);
for(var j=0; j<10; j++)
{
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
for(var i=0; i<randomLength; i++)
{
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname+1);
}
var divName = document.getElementById('names');
divName.innerHTML += '<li>' + randomName + '</li>';
randomName = "";
}
}
<form name="randomform">
<input type="button" value="Create" onClick="names()">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>
Just add var randomName = ''; after you first for loop, it will reset the previous value before generating new random string
function names()
{
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
console.log(randomLength);
for(var j=0; j<10; j++)
{
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
for(var i=0; i<randomLength; i++)
{
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname+1);
}
var divName = document.getElementById('names');
divName.innerHTML += '<li>' + randomName + '</li>';
}
}
<form name="randomform">
<input type="button" value="Create" onClick="names()">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>
I see two mistakes:
you do not reset randomName each time you should do.
you do not add each li in divName, but overwrite its whole content each time.
document.querySelector("#createButton").addEventListener("click",names);
function names()
{
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
console.log(randomLength);
for(var j=0; j<10; j++)
{
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
randomName= ""; //randomName have to be reset before create a new name
for(var i=0; i<randomLength; i++)
{
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname+1);
}
var divName = document.getElementById('names');
// instead of =, += allow you to add randomName to the divName content instead of replacing it.
divName.innerHTML += '<li>' + randomName + '</li>';
}
}
<form name="randomform">
<input type="button" value="Create" id="createButton">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>
Just add one line after print the li -
divName.innerHTML += '<li>' + randomName + '</li>';
randomName = "";
The issue that you're running into has to do with the scope of your randomName variable. Since that variable is initialized outside of your for loops, each time you add a substring to it, you're actually appending it to your previous string. To fix this in your current code, you can just move randomName into your first loop.
Also, you're creating your randomLength variable twice (once outside the loop and then on every iteration of your loop). Since the variable is only used to generate a random length string, you can safely remove the outer variable.
function names() {
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
for(var j=0; j<10; j++) {
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
for(var i=0; i<randomLength; i++) {
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname+1);
}
var divName = document.getElementById('names');
divName.innerHTML += '<li>' + randomName + '</li>';
}
}
<form name="randomform">
<input type="button" value="Create" onClick="names()">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>
I've updated your fiddle as well.
Move the declaration of randomName into the first for loop. It's not used in the scope it is declared and needs to be reset each time you generate an li.
function names() {
var txt = "abcdefghiklmnopqrstuvwxyz";
var name_length = 8;
for (var j = 0; j < 10; j++) {
var randomName = '';
var randomLength = Math.trunc(Math.random() * (8 - 4) + 4);
for (var i = 0; i < randomLength; i++) {
var rname = Math.floor(Math.random() * txt.length);
randomName += txt.substring(rname, rname + 1);
}
var divName = document.getElementById('names');
divName.innerHTML += '<li>' + randomName + '</li>';
}
}
<form name="randomform">
<input type="button" value="Create" onClick="names()">
<input type="text" name="randomfield">
</form>
<ul id="names">
</ul>

Calculate Percentage in HTML Table - jQuery

I am just trying to get the percentage in html table in second row
Database Consensus.
So just tried that jQuery
var TableData = new Array();
jQuery('#myTable tr').each(function(row, tr){
TableData[row]={
"1st" : jQuery.trim(jQuery(tr).find('td:eq(2)').text())
, "2nd" :jQuery.trim(jQuery(tr).find('td:eq(3)').text())
, "3rd" : jQuery.trim(jQuery(tr).find('td:eq(4)').text())
, "4th" : jQuery.trim(jQuery(tr).find('td:eq(5)').text())
}
});
TableData.shift();
TableData.sort();
var First = [];
var Second = [];
var Third = [];
var Fourth = [];
for (var i = 0; i < TableData.length - 1; i++) {
if (TableData[i + 1]['1st'] == TableData[i]['1st']) {
First.push(TableData[i]['1st']);
}
if (TableData[i + 1]['2nd'] == TableData[i]['2nd']) {
Second.push(TableData[i]['2nd']);
}
if (TableData[i + 1]['3rd'] == TableData[i]['3rd']) {
Third.push(TableData[i]['3rd']);
}
if (TableData[i + 1]['4th'] == TableData[i]['4th']) {
Fourth.push(TableData[i]['4th']);
}
}
var first = First.length;
var total = TableData.length;
var percent = first/total * 100;
jQuery('.1st').text(First[0] + "\n" + "(" + percent + "%"+")");
var second = Second.length;
var percent = second/total * 100;
jQuery('.2nd').text(Second[0] + "\n" + "(" + percent + "%"+")");
var third = Third.length;
var percent = third/total * 100;
jQuery('.3rd').text(Third[0] + "\n" + "(" + percent + "%"+")");
var fourth = Fourth.length;
var percent = fourth/total * 100;
jQuery('.4th').text(Fourth[0] + "\n" + "(" + percent + "%"+")");
But i am not getting right percentage :(
I am not have very good experience in jQuery but tried Here is demo
http://jsfiddle.net/bcHsy/33/
I am not much of a Fiddler, so I'm not sure that the link will even work, but I think that this might work:
Fiddle Link
I mostly changed the HTML in one section:
<tr>
<td align="center" valign="middle" bgcolor="#ffffff">
<p align="left">
<span style="color: #d89b5a;"><strong>Database Consensus</strong></span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;">-------</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="1st">L.Tunsil</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="2nd">C.Wentz</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="3rd">J.Ramsey</span>
</p>
</td>
<td>
<p align="center">
<span style="color: #d89b5a;" class="4th">M.Jack</span>
</p>
</td>
</tr>
and some of the JS:
var TableData = new Array();
var Picks = new Array();
jQuery('#myTable tr').each(function(row, tr){
if (row == 1) {
Picks[0] = jQuery.trim(jQuery(tr).find('td:eq(2)').text());
Picks[1] = jQuery.trim(jQuery(tr).find('td:eq(3)').text());
Picks[2] = jQuery.trim(jQuery(tr).find('td:eq(4)').text());
Picks[3] = jQuery.trim(jQuery(tr).find('td:eq(5)').text());
}
TableData[row]={
"1st" : jQuery.trim(jQuery(tr).find('td:eq(2)').text())
, "2nd" :jQuery.trim(jQuery(tr).find('td:eq(3)').text())
, "3rd" : jQuery.trim(jQuery(tr).find('td:eq(4)').text())
, "4th" : jQuery.trim(jQuery(tr).find('td:eq(5)').text())
}
});
TableData.shift();
TableData.shift();
TableData.sort();
var First = [];
var Second = [];
var Third = [];
var Fourth = [];
for (var i = 0; i < TableData.length; i++) {
if (TableData[i]['1st'] == Picks[0]) {
First.push(TableData[i]['1st']);
}
if (TableData[i]['2nd'] == Picks[1]) {
Second.push(TableData[i]['2nd']);
}
if (TableData[i]['3rd'] == Picks[2]) {
Third.push(TableData[i]['3rd']);
}
if (TableData[i]['4th'] == Picks[3]) {
Fourth.push(TableData[i]['4th']);
}
}
var first = First.length;
var total = TableData.length;
var percent = first/total * 100;
jQuery('.1st').text(First[0] + "\n" + "(" + percent + "%"+")");
var second = Second.length;
var percent = second/total * 100;
jQuery('.2nd').text(Second[0] + "\n" + "(" + percent + "%"+")");
var third = Third.length;
var percent = third/total * 100;
jQuery('.3rd').text(Third[0] + "\n" + "(" + percent + "%"+")");
var fourth = Fourth.length;
var percent = fourth/total * 100;
jQuery('.4th').text(Fourth[0] + "\n" + "(" + percent + "%"+")");

Why does my alarmclock script stop working?

It only works once. At second button click, nothing occurs.
If I change budilnik variable at i_budilnik or var budilnik, it doesn't work even once!
Where is the problem?
<div>
<form name="alert">
<input type="text" name="hour" />
<input type="text" name="min" />
<input type="button" value="ok" onclick="budilnik(this.form)">
</form><font color=#660000 size=20 face=Tahoma><span id="hours"></span>
</div>
<script type="text/javascript">
function budilnik(form) {
budilnik = 1;
min = form.min.value;
hour = form.hour.value;
}
obj_hours = document.getElementById("hours");
function wr_hours() {
time = new Date();
time_min = time.getMinutes();
time_hours = time.getHours();
time_wr = ((time_hours < 10) ? "0" : "") + time_hours;
time_wr += ":";
time_wr += ((time_min < 10) ? "0" : "") + time_min;
time_wr = time_wr;
obj_hours.innerHTML = time_wr;
if (i_budilnik == 1) {
if (min == time_min) {
if (hour == time_hours) {
alert('welldone');
budilnik = 0;
}
}
}
}
wr_hours();
setInterval("wr_hours();", 1000);
</script>
You call the function wr_hours(); only once... with the onclick budilnik is called, but that doesn't touch wr_hours again. The first time the code is run, because the page is loaded, but after that, with the onclick only the values of min and hour are set again.
edit: you shouldn't call your form "alert", since that's a reserved word in javascript, same for the variable min. also: the variables min and hour are defined in the function budilnik, but they're not known outside this scope. I also renamed the variable budilnik to a global variable justonce to make sure you can check it outside the scope of budilnik. I rewrote your code a bit:
<html>
<body>
<div>
<form name="frm">
<input type="text" name="hour" />
<input type="text" name="mins"/>
<input type="button" value="ok" onclick="justonce=1;">
</form>
<font color=#660000 size=20 face=Tahoma><span id="hours"></span></font>
</div>
</body>
</html>
<script type="text/javascript">
obj_hours=document.getElementById("hours");
justonce=0;
function wr_hours()
{
time=new Date();
time_min=time.getMinutes();
time_hours=time.getHours();
time_wr=((time_hours<10)?"0":"")+time_hours;
time_wr+=":";
time_wr+=((time_min<10)?"0":"")+time_min;
obj_hours.innerHTML=time_wr;
if (justonce==1 && frm.mins.value==time_min && frm.hour.value==time_hours) {
alert('welldone');
justonce=0;
}
}
setInterval("wr_hours();",1000);
</script>
Your function wr_hours could be a lot shorter by the way:
function wr_hours()
{
time=new Date();
obj_hours.innerHTML=("%02d",time.getHours())+":"+("%02d",time.getMinutes());
if (justonce==1
&& frm.mins.value==time.getMinutes()
&& frm.hour.value==time.getHours()) {
alert('welldone');
justonce=0;
}
}
How about this?
You can't hear the"alarm" in this code, so you have to download the sound you like, rewrite a part of the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=shift_jis">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<bgsound id="bgm" src="222.mid" loop="-1">
<TITLE>Yokai clock~The digital clock changes to the analogue one!?~</TITLE>
<SCRIPT type="text/javascript">
<!--
var flg =0;
function timeCheck(){
Now = new Date();
Hour = Now.getHours();
Min = Now.getMinutes();
Sec = Now.getSeconds();
if(Hour <= 9) {
Hour = "\u0020" + Hour;
  }
    if(Min <= 9) {
Min = "0" + Min;
  }
if(Sec <= 9) {
Sec = "0" + Sec;
  }
document.sampleForm.dspTime.value=Hour + ":" + Min + ":" + Sec;
if((flg == 1)&&(document.sampleForm.alarmH.value == Hour)&&(document.sampleForm.alarmM.value == Min)){
document.getElementById('bgCol').value="333.wav", selectBgm(document.getElementById('bgCol')),
document.getElementById('star_clock').style.visibility="hidden", document.getElementById('clock').style.visibility="visible";
flg=-1; //*One figure other than 0 and 1
  }
}
function changeFlg(){
if(flg == 0){
    document.sampleForm.setAlarm.value=" alarmOFF ";
document.getElementById("bgCol").value="";
        selectBgm(document.getElementById('bgCol'));
     flg =1;
}else{
document.sampleForm.setAlarm.value=" alarm ON ";
document.getElementById("bgms").reset();
selectBgm(document.getElementById('bgCol'));
document.getElementById('star_clock').style.visibility="visible";
document.getElementById('clock').style.visibility="hidden";
       flg =0;
}
}
setInterval(timeCheck,100);
window.onload = timeCheck;
//-->
</SCRIPT>
<script type="text/javascript">
<!--
function selectBgm(e){
var selectedIndex = e.selectedIndex;
document.getElementById("bgCol").style.background=e[selectedIndex].style.backgroundColor;
bgm.src= e[selectedIndex ].value;
document.getElementById("bgCol").value=e[selectedIndex].value;
}
//-->
</script>
</head>
<BODY color="gold" bgcolor="black">
<div id="clock" style="visibility:hidden">
<div id="Od" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Of" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Oh" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Om" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
<div id="Os" style="position:absolute;top:0px;left:0px">
<div style="position:relative">
</div>
</div>
</div>
<script type="text/javascript">
(function(){
"use strict";
function $(sel)
{
return document.getElementById(sel);
}
function $$(sel)
{
if (typeof document.getElementsByClassName === 'undefined')
{
return document.getElementsByName(sel);
}
return document.getElementsByClassName(sel);
}
var dCol = '00ff00', //date colour.
sCol = 'ff0000', //seconds colour.
mCol = '008000', //minutes colour.
hCol = '008000', //hours colour.
fCol = '0000ff', //face color
ClockHeight = 40,
ClockWidth = 40,
ClockFromMouseY = 0,
ClockFromMouseX = 100,
d = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
m = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
date = new Date(),
day = date.getDate(),
year = date.getYear() + 1900;
var TodaysDate = " " + d[date.getDay()] + " " + day + " " + m[date.getMonth()] + " " + year;
var D = TodaysDate.split('');
var H = '...';
H = H.split('');
var M = '....';
M = M.split('');
var S = '.....';
S = S.split('');
var Face = '1 2 3 4 5 6 7 8 9 10 11 12',
font = 'Helvetica, Arial, sans-serif',
size = 1,
speed = 0.6;
Face = Face.split(' ');
var n = Face.length;
var a = size * 10;
var ymouse = 0,
xmouse = 0,
scrll = 0,
props = '<span style="font-family:' + font + ';font-size:' + size + 'em; color:#' + fCol + '">',
props2 = '<span style="font-family:' + font + ';font-size:' + size + 'em; color:#' + dCol + '">';
var Split = 360 / n;
var Dsplit = 360 / D.length;
var HandHeight = ClockHeight / 4.5;
var HandWidth = ClockWidth / 4.5;
var HandY = -7,
HandX = -2.5,
step = 0.06,
currStep = 0,
y = [],
x = [],
Y = [],
X = [],
Dy = [],
Dx = [],
DY = [],
DX = [];
var i;
for (i = 0; i < n; i++)
{
y[i] = 0;
x[i] = 0;
Y[i] = 0;
X[i] = 0;
}
for (i = 0; i < D.length; i++)
{
Dy[i] = 0;
Dx[i] = 0;
DY[i] = 0;
DX[i] = 0;
}
var wrapper = $('clock');
var html = ''
// Date wrapper
html = '';
for (i = 0; i < D.length; i++)
{
html += '<div class="Date" name="Date" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props2 + D[i] + '</span></div>';
}
$('Od').children[0].innerHTML = html;
// Face wrapper
html = '';
for (i = 0; i < n; i++)
{
html += '<div class="Face" name="Face" style="position:absolute;top:0px;left:0;height:' + a + ';width:' + a + ';text-align:center">' + props + Face[i] + '</span></div>';
}
$('Of').children[0].innerHTML = html;
// Hours wrapper
html = '';
for (i = 0; i < H.length; i++)
{
html += '<div class="Hours" name="Hours" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + hCol + ';text-align:center;font-weight:bold">' + H[i] + '</div>';
}
$('Oh').children[0].innerHTML = html;
// Minute wrapper
html = '';
for (i = 0; i < M.length; i++)
{
html += '<div class="Minutes" name="Minutes" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + mCol + ';text-align:center;font-weight:bold">' + M[i] + '</div>';
}
$('Om').children[0].innerHTML = html;
// Seconds wrapper
html = '';
for (i = 0; i < S.length; i++)
{
html += '<div class="Seconds" name="Seconds" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:' + sCol + ';text-align:center;font-weight:bold">' + S[i] + '</div>';
}
$('Os').children[0].innerHTML = html;
// Mouse move event handler
function Mouse(evnt)
{
if (typeof evnt === 'undefined')
{
ymouse = event.Y + ClockFromMouseY;
xmouse = event.X + ClockFromMouseX;
}
else
{
ymouse = evnt.clientY + ClockFromMouseY;
xmouse = evnt.clientX + ClockFromMouseX;
}
}
document.onmousemove = Mouse;
function ClockAndAssign()
{
var time = new Date();
var secs = time.getSeconds();
var sec = -1.57 + Math.PI * secs / 30;
var mins = time.getMinutes();
var min = -1.57 + Math.PI * mins / 30;
var hr = time.getHours();
var hrs = -1.575 + Math.PI * hr / 6 + Math.PI * parseInt(time.getMinutes(), 10) / 360;
$('Od').style.top = window.document.body.scrollTop;
$('Of').style.top = window.document.body.scrollTop;
$('Oh').style.top = window.document.body.scrollTop;
$('Om').style.top = window.document.body.scrollTop;
$('Os').style.top = window.document.body.scrollTop;
for (i = 0; i < n; i++)
{
var F = $$('Face')[i];
F.style.top = y[i] + ClockHeight * Math.sin(-1.0471 + i * Split * Math.PI / 180) + scrll;
F.style.left = x[i] + ClockWidth * Math.cos(-1.0471 + i * Split * Math.PI / 180);
}
for (i = 0; i < H.length; i++)
{
var HL = $$('Hours')[i];
HL.style.top = y[i] + HandY + (i * HandHeight) * Math.sin(hrs) + scrll;
HL.style.left = x[i] + HandX + (i * HandWidth) * Math.cos(hrs);
}
for (i = 0; i < M.length; i++)
{
var ML = $$('Minutes')[i].style;
ML.top = y[i] + HandY + (i * HandHeight) * Math.sin(min) + scrll;
ML.left = x[i] + HandX + (i * HandWidth) * Math.cos(min);
}
for (i = 0; i < S.length; i++)
{
var SL = $$('Seconds')[i].style;
SL.top = y[i] + HandY + (i * HandHeight) * Math.sin(sec) + scrll;
SL.left = x[i] + HandX + (i * HandWidth) * Math.cos(sec);
}
for (i = 0; i < D.length; i++)
{
var DL = $$('Date')[i].style;
DL.top = Dy[i] + ClockHeight * 1.5 * Math.sin(currStep + i * Dsplit * Math.PI / 180) + scrll;
DL.left = Dx[i] + ClockWidth * 1.5 * Math.cos(currStep + i * Dsplit * Math.PI / 180);
}
currStep -= step;
}
function Delay()
{
scrll = 0;
Dy[0] = Math.round(DY[0] += ((ymouse) - DY[0]) * speed);
Dx[0] = Math.round(DX[0] += ((xmouse) - DX[0]) * speed);
for (i = 1; i < D.length; i++) {
Dy[i] = Math.round(DY[i] += (Dy[i - 1] - DY[i]) * speed);
Dx[i] = Math.round(DX[i] += (Dx[i - 1] - DX[i]) * speed);
}
y[0] = Math.round(Y[0] += ((ymouse) - Y[0]) * speed);
x[0] = Math.round(X[0] += ((xmouse) - X[0]) * speed);
for (i = 1; i < n; i++) {
y[i] = Math.round(Y[i] += (y[i - 1] - Y[i]) * speed);
x[i] = Math.round(X[i] += (x[i - 1] - X[i]) * speed);
}
ClockAndAssign();
setTimeout(Delay, 20);
}
Delay();
}());
</script>
<form id="bgms" style="text-align:right">
<SELECT id="bgCol" style="background:#87cefa"; onchange="selectBgm(this);">
<OPTION style="background:silver" value="" >STOP</OPTION>
<OPTION style="background:#87cefa" value="222.mid" selected>CLASSIC</OPTION>
<OPTION style="background:yellowgreen" value="333.wav">ALARM</OPTION>
</SELECT>
</form>
<FORM NAME="sampleForm" style="text-align:center">
 <font id="star_clock">
<INPUT id="Alarmy" type="text"STYLE="color:deeppink; background-color:black; font-size:25px; border:none;" size=7 NAME="dspTime">
 </font>
<br><br>
<br><br>
 <div>
★
<INPUT type="text" name="alarmH" size=2 value="00">
<INPUT type="text" name="alarmM" size=2 value="00">
<INPUT type="button" id="setAlarm" name="setAlarm" value=" alarm ON " onClick="changeFlg();">
★
 </div>
</FORM>
</BODY>
</HTML>

Categories

Resources