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>
Related
I have a random grid generator that asks how big you want the grid. If you input 5 it will produce a 5x5 grid with random numbers in it, or a 10x10 grid with random numbers etc.
I now need to take those random numbers once the grid is produced and display the average of the random numbers. I can't seem to get this part to work, because there are different numbers each time you generate a new grid.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
This is my code and I just can't seem to figure out how to go about this.
Here is a simple way, just accumulate the randNumber you calculated, then divide by the total number of cells.
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var avg = 0;
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
avg += randNumber;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
avg /= num*num;
str = str + "</table>" + "<span>Average is " + avg + "</span>";
result.innerHTML = str;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
A couple of additions to what you gave us to start with.
var button = document.getElementById('gridSize');
var total = 0;
var divisor = 0;
button.onclick = function(e) {
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
total = total+randNumber;
++divisor;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
var average = total / divisor;
var averageSpan = document.getElementById('average');
averageSpan.innerText = average;
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
Average: <span id="average"></span>
<div id="wrapper"></div>
Also a fiddle: https://jsfiddle.net/xpvt214o/775850/
Well, create a variable where you keep summing all generated random numbers.
At the end, get that number and divide by the area of the grid (the number user typed * the number user typed num*num)
Like below:
var button = document.getElementById('gridSize');
button.onclick = function(e) {
var total = 0;
result = document.getElementById('wrapper');
num = parseInt(document.getElementById('grid').value);
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td style="background: red;">';
}
else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
str += '<td style="background: blue;">';
}
else {
str += "<td>";
}
total += parseInt(randNumber);
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
console.log("Avg.: ", total/(num*num) || 0)
}
<form name="tablegen">
<input type="text" name="grid" id="grid"/>
<input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
There are already some good answers. Here is a different approach. I also "cleaned up" the HTML and code a bit:
let button = document.getElementById("generatorButton");
button.onclick = function(e) {
document.getElementById("grid").innerHTML = createGrid();
document.getElementById("full-average").innerText = getGridAverage();
document.getElementById("mod3-average").innerText = getGridAverage(".mod3");
document.getElementById("mod2-average").innerText = getGridAverage(".mod2");
}
function createGrid()
{
gridSize = parseInt(document.getElementById('gridSize').value);
let str = "<table border='2'>";
for (let row = 0; row < gridSize; row++) {
str += "<tr>";
for (let col = 0; col < gridSize; col++) {
var randNumber = Math.floor(Math.random() * 100) + 1;
if (randNumber % 3 === 0) {
str += '<td class="mod3">';
}
else if (randNumber % 2 === 0) {
str += '<td class="mod2">';
}
else {
str += "<td>";
}
str += randNumber + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
return str;
}
function getGridAverage(cssClass)
{
if (cssClass == undefined) cssClass = "";
let cells = document.querySelectorAll("#grid td" + cssClass);
if (cells.length > 0)
{
let sum = 0;
for (const cell of cells)
{
sum += parseInt(cell.innerHTML);
}
return sum / cells.length;
}
else
return 0;
}
.mod3 {
background-color: red;
}
.mod2 {
background-color: blue;
}
<form name="tablegen">
<input type="text" id="gridSize" placeholder="Enter grid size (e.g.: 5)" />
<input type="button" id="generatorButton" value="Generate Grid!" />
</form>
<div id="grid"></div>
<div>Full Average:<span id="full-average">n/a</span></div>
<div>Mod3 (red) Average:<span id="mod3-average">n/a</span></div>
<div>Mod2 (blue) Average:<span id="mod2-average">n/a</span></div>
Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good
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>△y</th>
<th>△<sup>2</sup>y</th>
<th>△<sup>3</sup>y</th>
<th>△<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>△y</th>
<th>△<sup>2</sup>y</th>
<th>△<sup>3</sup>y</th>
<th>△<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>△y</th>
<th>△<sup>2</sup>y</th>
<th>△<sup>3</sup>y</th>
<th>△<sup>4</sup>y</th>
</tr>
</table>
<button type="button" onclick="submitForCalc()">Submit</button>
<div id="tablePrint"></div>
<script src="babbCore.js">
</script>
</body>
I'm beginner in coding. I've tried to find similar problem on SO but with no proper result.
I'm writting a code where HTML form sends its value to an object's property, then I want to print it in document using innerHTML method. I save object in array so then I can manipulate them.
Some problems appears when I add one more dimension to my array (arr[i][j] in code below - 2nd dimension will be needed further) - then object's properties change to "undefined" when printed. What should I do to get access to object's properties in array's 2nd dimension (using JS only)? This is my JS code:
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
and HTML in body:
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick=A ddProduct()>
Try substituting
onclick="AddProduct()"
for
onclick=A ddProduct()
at html; and add [0] at
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
for
content += arr[i][j].name + ' price is ' + arr[i][j].price + '<br>';
as you pushed an array containing an object to arr at first for loop. To reference the index of the array, use bracket notation to retrieve object at index 0 of array in arr
var pro = 0;
var ctg = 1;
var arr = new Array(ctg);
arr[0] = new Array(pro)
function AddProduct() {
var n = document.getElementById('name').value;
var p = document.getElementById('price').value;
pro++;
for (i = arr[0].length; i < pro; i++) {
arr[0].push([{
name: n,
price: p
}]);
}
var content = '';
for (i = 0; i < arr.length; i++) {
for (j in arr[i]) {
content += arr[i][j][0].name + ' price is ' + arr[i][j][0].price + '<br>';
}
}
document.getElementById('p').innerHTML = content;
};
<p id="p"></p>
<input type="text" id="name" placeholder="name">
<br>
<input type="text" id="price" placeholder="price">
<br>
<input type="button" value="OK" onclick="AddProduct()">
I have a query in javascript.. Please check the below image
In Above image :
First Input Box is Description
2nd Input Box is Qty
3rd is Value
I have got total qty using below script onchange of textbox :
function findTotal(){
var total = 0;
var $changeInputs = $('input.qtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
$("#totalvval").val(total);
}
I have got total Value using below :
function qfindTotal(){
var total = 0;
var $changeInputs = $('input.qqtyValue');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.qtotal').text(total);
$("#totalqval").val(total);
if(total>10000){
alert("Amount should not be greater than 10000");
}
}
My query is that we need total of qty x value + qty x value + qty x value =total
You can try something like this:
Fiddle
Code
function createHTML() {
var html = "";
for (var i = 0; i < 3; i++) {
html += "<input type='text' class='qty' id='txtQty_" + i + "' onblur='updateTotal()' />";
html += "<input type='text' class='cost' id='txtQty_" + i + "' onblur='updateTotal()'/>";
html += "<br/>"
}
html += "Qty Total: <span id='qty_total'>0</span>";
html += "Cost Total: <span id='cost_total'>0</span>";
document.getElementById("content").innerHTML = html
}
function updateTotal() {
var qty = document.getElementsByClassName("qty");
var cost = document.getElementsByClassName("cost");
var total_qty = 0;
var total_cost = 0;
for (var i = 0; i < qty.length; i++) {
if (qty[i].value && cost[i].value) {
total_cost += qty[i].value * cost[i].value;
total_qty += parseInt(qty[i].value);
}
}
document.getElementById("qty_total").innerHTML = total_qty;
document.getElementById("cost_total").innerHTML = total_cost;
}
(function() {
createHTML();
})()
<div id="content"></div>