Multiply Rows With Column in JavaScript using loops - javascript

I want to multiply rows with columns inside HTML table each td contains input type elements and each is dynamic means they can be created more at runtime but the process of multiplication will remain the same.
Click here to see image
below is my code
var inputs = $(".volo");
var id = 0;
for (var i = 0; i < inputs.length; i++) {
for (var j = 0; j < r.length; j++) {
if (i < r.length) {
alert(parseFloat($(inputs[i]).val()) + "*" + r[j]);
j = 0;
} else {
j = j + 1;
alert(parseFloat($(inputs[i]).val()) + "*" + r[j]);
}
break;
}
}
above code works fine when a number of rows and columns are 2 .inputs contains values coming from one type of tds and r array contains values coming from different tds.length of inputs array will always be greater than r array.

The first loop should loop the column while the second loop should be the row loop, assume you need to read the input you can do this with jquery ,let x be row while y be column
$(`#volX${x}Y${y}` ).val()
Your Add Chemical Vol button must be able to create specific mapping of id="volXnumYnum" input.
play around with that it might help you solve your problem

Related

Write a program that asks for an input and generates a pyramid of stars that has that many layer, adding 2 stars per later

I'm trying to create a program that generates a a pyramid of stars. The amount of layers the pyramid has are dependent on the user's input. For example, if the user entered a 2, it would display something like
*
***
^As you can see, it adds two stars per layer and the number of layers is too. I've already made the basic code for this. I have figured out how to make the layers, but I can't seem to figure out how to get the number of layers right. I figured out of how get 2 stars to appear on each new layer, but am having trouble centering and properly displaying the right amount of layers. (My pyramid is centered poorly and it isn't symmetrical. Here is my code right now. I added some comments.
For some context, I'll include the a picture of how I want the pyramid to look.
As you can see, when the user enters 4 for instance, there are 4 layers, and each layer increases by two on each side. However, with my current code, when the user enter a 4, there aren't four layers and I'm not sure how to achieve that. Please don't use CSS to achieve the centering, I want to keep it JavaScript only.
var num = prompt("Enter a number..");
for (var i = 1; i <= num; i = i + 2) {
for (var j = 1; j <= (num - i); j = j + 1) {
document.write(" ");
}
for (var k = 1; k <= i; k = k + 1) {
document.write("* ");
}
document.write("<br/>");
}
you need to fix the spaces of course but the reason you can't get the expected number of rows is you are increasing i +2. i needs to be i++
EDIT: Spaces are also fixed.
var num = prompt("Enter a number..");
for (var i = 1; i <= num; i++) {
for (var j = 0; j < num-i; j++) {
document.write(" ");
}
for (var k = 1; k <= i; k++) {
document.write("*");
}
document.write("<br/>");
}
You should think it is a matrix and each row length depends with your layer bunber which formula is n*2-1 and set to it in middle of row length

Javascript Dynamically build HTML table with button cell

Trying to get my dynamic table to have a button in last column. Have had no luck. Any help much appreciated.
var removeRow=document.createElement("BUTTON");
//Add the data rows.
for (var i = 1; i < data.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < 3; j++) {
var cell = row.insertCell(-1);
if (j==0) {
cell.innerHTML = data[i].userId}
if (j==1) {
cell.innerHTML = data[i].id}
if (j==2) {
cell.innerHTML = data[i].title}
if (j==3) {
cell.appendChild(removeRow)// Not working when replace data[i].field with button variable.
}
}
In your loop, j never gets to 3 (it says j < 3 in your second for statement).
If you change that to j < 4 or j <= 3 it should work.
Apart from that, you are only creating one BUTTON element, which you will be appending to all rows. Every time you append it to a row, it will be removed from the previous row it was on, so you'll still be left with just one button.

Javascript print square using for loop and conditional statement only

Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must combine for loops and if statements.
This is what I have so far and I feel pretty close but I just can't get the second line to display. I know this can be done via two for loops, (one for iteration of the variable and another for spaces). But this is not how I have been asked to solve this problem.
Here is my code:
var size = 3;
let i;
for(i = 0; i < size; i++) {
print ("*");
if (size === i){
println ("");
}
}
For context, this is all taking place int he professors homemade learning environment.
You could use nested for loops and take a line break after each filled line.
function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }
var size = 5,
i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
print("*");
}
println("");
}
<pre id="out"></pre>
Single loop with a check if i is unequal to zero and if the remainder is zero, then add a line break.
Using:
=== identity/strict equality operator checks the type and the value, for example if both are numbers and if the value is the same,
!== non-identity/strict inequality operator it is like above, but it checks the oposite of it,
% remainder operator, which returns a rest of a number which division returns an integer number.
&& logical AND operator, which check both sides and returns the last value if both a truthy (like any array, object, number not zero, a not empty string, true), or the first, if it is falsy (like undefined, null, 0, '' (empty string), false, the oposite of truthy).
function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }
var size = 5,
i;
for (i = 0; i < size * size; i++) {
if (i !== 0 && i % size === 0) {
println("");
}
print("*");
}
<pre id="out"></pre>
Well the for loop is only iterating 3 times, printing the first line. If you want a square you'll have to print 9 stars total, right? So i'm assuming, is this is the approach you'd go for, you would need to iterate not until size, but until size * size.
I'm using console.log to 'print' the square:
var dimension = 10;
var edge = '*';
var inside = ' ';
var printLine;
for (var i = 1; i <= dimension; i++) {
if (i === 1 || i === dimension) {
printline = Array(dimension + 1).join(edge);
} else {
printline = edge + Array(dimension - 1).join(inside) + edge;
}
console.log(printline);
}
Note that in the following example, an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements:
Array(11).join('a'); // create string with 10 as "aaaaaaaaaa"
You wanna make a square of * where the size is the number of * on its sides?
Let's split a task into 3 parts:
where you print top side like *****
where you print middle (left and right sides) like * *
where you print bottom (same as top)
Now let's code that, I kept the code as simple as possible, this can be done in fewer lines but I think this will be easier to understand for beginners:
var size = 5;
var i = 0;
// top
for (i = 0; i < size; i++)
console.log("*");
//middle
for (var j = 0; j < size - 2; j++){
console.log("\n"); // go to next row
// middle (2 on sides with size-2 in between)
console.log("*");
for (i = 0; i < size-2; i++)
console.log(" ");
console.log("*\n"); // goes to new row as well
}
// same as top
for (i = 0; i < size; i++)
console.log("*");
Full square is even simpler:
var size = 5;
var i = 0;
for (var i = 0; i < size; i++){ // iterates rows
for (var j = 0; j < size; j++) // iterates * in row
console.log("*");
console.log("\n") // moves to new row
}
In order to print a row, you print same sign X times. Well, to print X rows we can use just that 1 more time (only this time we are iterating over a different variable (j is * in a row, i is a number of rows).
After a row is made we go to go to next row with \n.
As for
it must contain if statement
Put this at the end:
if (youCanHandleTheTruth) console.log("It's a terrible practice to tell students their solution MUST CONTAIN CODEWORDS. If you need them to showcase something, write appropriate task that will require them to do so.");

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

I'm having difficulty populating a two dimensional array with random Boolean values and then reading those values back out in JavaScript

I'm working on a really simple cellular automata program in JavaScript. For right now I just want to write a bunch of random Boolean values to a two-dimensional array and then read that array back to be manipulated or displayed in some way.
var dimension = 5;
var grid = new Array();
for (x = 0; x < dimension; x++) {
grid[x] = new Array();
}
//populate grid
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
grid[i,j] = Math.floor(Math.random()*2);
document.write(grid[i,j]);
}
}
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
document.write(grid[i,j]);
}
}
So, I've whittled the code down to a few nested for loops where I cycle through and populate the array and then print it back. Note that the output generated during the population loop is what I want, random values. But when I read the array back, it seems like the last row (I think it's really a column, but it's displayed horizontally) has been copied to all the others...
I've done this sort of thing before in other languages and never had a problem like this.
I'm new to this community and JavaScript in general so this might be a dumb questing or I may not have presented it helpfully. I would really appreciate any help or advice on how I can improve my question.
Array indexes in JavaScript are not comma seperated. You need to use brackets. So for your two dimensional array it will be:
grid[i][j]; // not grid[i,j]

Categories

Resources