HTML Javascript loop to create a table - javascript

I need to create a table with html javascript which has the number of cells that are equal to the user input.
Basically, at the start, the user is prompted to enter a number and then a table is created that has number of cells which are equal to the user input number.
The number of columns should be 10.
The tricky part is to get the number of rows.
For example, if the user enters 30, then the table has 10 columns and 3 rows.
The problem comes, if the number is not a multiple of 10.
For example, if the user enters 32, with the code I created I can still get only 10 columns and 3 rows, which is still 30 cells.
In addition, I need to number the cells as well.
Can anyone help me out of this mess?
A picture of the table I need
<html>
<head>
<style>
table{width: 70%;}
</style>
<script>
let num= window.prompt("What is the loop maximum.? (between 1 and 500)")
if(num<0 || num>500)
{
window.alert("Warning! Must be between 1 and 500. Setting to default
100")
}
</script>
</head>
<body>
<h1>Javascript Loops and Functions</h1><br>
<script>
document.write("<table border=1>")
for (row=1; row<=num/10; row++) {
document.write("<tr>")
for (col=1; col<=10; col++) {
document.write("<td>"+ num + "</td>")
}
document.write("</tr>")
}
document.write("</table>")
</script>
</body>

Problem Description
We need a way to create a table of numbers starting at 0 till the last number provided to us by the user.
The last number must be between 1 and 500. (You can adjust the range as per your need.)
Solution Implemented in above code:
Columns - 10, Number = 30, Rows = (num / columns = 3)
Problems faced in above code:
Columns - 10, Number = 32, Rows = (num / columns = 3)
The no of rows is still 3, but we need atleast 4 rows to accomodate 32 numbers in 10 columns.
Data in each column printed is 32 if you enter 32 via prompt.
Visual Representation?
To understand the problem in our proposed solution, let us write what's happening under the hood.
Num / columns = No_of_Rows
30 / 10 = 3.0
31 / 10 = 3.1
32 / 10 = 3.2
33 / 10 = 3.3
34 / 10 = 3.4
35 / 10 = 3.5
36 / 10 = 3.6
37 / 10 = 3.7
38 / 10 = 3.8
39 / 10 = 3.9
40 / 10 = 4.0
300 / 10 = 30.0
301 / 10 = 30.1
...
This calculation provides us a hint that if our formula to compute no of rows is incorrect. The error occurs due to remainder in our code.
If we could somehow use this remainder to caluclate no of rows, then issue should be fixed.
What if we could increment no of rows by 1 if remainder is greater than 0 but less than 10? I think you got the point.
Now, It's time to modify our code to consider remainder.
// Read it as: if num modulo 10 is greater than 0 and less then 10 then increment row by 1 else don't
let rows = ((num % 10) > 0 && (num % 10) < 10) ? (num / 10) + 1 : num / 10;
So, replacing our no of rows by above code should fix the issue.
Solution 1
Here is complete code with issue fixed:
<html>
<head>
<style>
table {
width: 70%;
}
</style>
<script>
let num = window.prompt("What is the loop maximum.? (between 1 and 500)");
if (num < 0 || num > 500) {
window.alert(
"Warning! Must be between 1 and 500. Setting to default 100"
);
}
</script>
</head>
<body>
<h1>Javascript Loops and Functions</h1>
<br />
<script>
document.write("<table border=1>");
let rows = num % 10 > 0 && num % 10 < 10 ? num / 10 + 1 : num / 10;
for (row = 1; row <= rows; row++) {
document.write("<tr>");
for (col = 1; col <= 10; col++) {
document.write("<td>" + num + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
</html>
Final Solution
Fix problem of printing same no in all columns:
Fix problem of printing nos in all 10 columns when not required(in case of 32)
<html>
<head>
<style>
table {
width: 70%;
}
</style>
<script>
let num = window.prompt("What is the loop maximum.? (between 1 and 500)");
if (num < 0 || num > 500) {
window.alert(
"Warning! Must be between 1 and 500. Setting to default 100"
);
}
</script>
</head>
<body>
<h1>Javascript Loops and Functions</h1>
<br />
<script>
document.write("<table border=1>");
// Formula to calculate no of rows.
let rows = num % 10 > 0 && num % 10 < 10 ? num / 10 + 1 : num / 10;
let count = 0; // Variable to keep track of numbers printed till now.
for (row = 1; row <= rows; row++) {
document.write("<tr>");
for (let i = 1; i <= 10; i++) {
if (count >= num) break; // Exit early if we already printed nos in less than 10 columns.
document.write("<td>" + count + "</td>");
count++;
}
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
</html>

In this case you don't need a number of rows. You only need to trigger adding <td> elements into <tr> if cellNumber % columns === 0 inside your loop.
You forgot about:
number that you got from window.prompt ... is in fact a string - you have to convert it to an integer with parseInt()
set that default value to 100 as you mentioned in the alert ^^
I must also mention that using document.write() is considered to be a bad practise. It's better to use document.createElement() to create DOM elements and parentElement.appendChild(element) to insert DOM elements into another DOM elements.
With using document.write() you also limit yourself to adding elements into <body>. Handling with DOM elements gives you more possibilities - with them you can put such structures anywhere you want.
Here's a code snippet of a function which generates such table as a DOM element.
const generateTable = (cells, columns = 10) => {
const table = document.createElement('table');
let row = document.createElement('tr');
for(let i = 1; i <= cells; ++i){
const cell = document.createElement('td');
cell.textContent = i - 1;
row.appendChild(cell);
if(i % columns === 0 || i === cells){
table.appendChild(row);
row = document.createElement('tr');
}
}
return table;
};
You can pin a result of such function for example to body DOM element just like in an example below:
const table = generateTable(123, 12);
document.body.appendChild(table);
Here's my snippet matching it all together with all mentioned cases implemented:
const generateTable = (cells, columns = 10) => {
const table = document.createElement('table');
let row = document.createElement('tr');
for(let i = 1; i <= cells; ++i){
const cell = document.createElement('td');
cell.textContent = i - 1;
row.appendChild(cell);
if(i % columns === 0 || i === cells){
table.appendChild(row);
row = document.createElement('tr');
}
}
return table;
};
window.addEventListener("DOMContentLoaded", () => {
const numString = window.prompt("What is the loop maximum.? (between 1 and 500)");
let num = parseInt(numString);
if (num < 0 || num > 500) {
window.alert("Warning! Must be between 1 and 500. Setting to default 100");
num = 100;
}
const table = generateTable(num);
document.body.appendChild(table);
})
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
table{
border-collapse: collapse;
}
td{
text-align: center;
padding: 7px 14px;
border: 1px grey solid;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Table loop example</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Docs reference:
https://developer.mozilla.org/pl/docs/Web/API/Node/appendChild - appending child to parent
https://developer.mozilla.org/pl/docs/Web/API/Document/createElement - creating a DOM element
https://developer.mozilla.org/pl/docs/Web/API/Element - some knowledge about DOM elements
https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/parseInt - parseInt()

function generateTable(n, columnCount=10) {
document.write("<table border=1>");
document.write("<tr>");
for (i = 0; i < n; i++) {
if (i % columnCount === 0) {
document.write("</tr>");
document.write("<tr>");
}
document.write("<td>" + i + "</td>");
}
document.write("</tr>");
document.write("</table>");
}
That should work for you ^^

Related

JAVASCRIPT nested loops - triangle exercise from user input

I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number ex enter 5
This is what I want
**5
6 6
7 7 7
8 8 8 8
9 9 9 9 9
10 10 10 10 10**
Each line the number is increased by 1. I can't get my code to increase by 1.
I keep getting
5
5 5
5 5 5
5 5 5 5
5 5 5 5 5
Anyone have any suggestions? Thanks
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= 6; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write(num = num +1; "<br>");
}
<p id="num"> </p>
You just have to use the entered number as the loop upper limit:
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= num; i++) {
//loop 2
for (y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
This syntax is entirely invalid:
document.write(num = num +1; "<br>");
You're somehow confusing calling a function with defining a for loop. Those are two entirely different things.
Don't randomly try to munge together separate operations. Put each operation on its own line of code. The two operations you want to perform are:
Add 1 to num
Output a <br> element
These are separate operations. So separate them:
num = num +1;
document.write("<br>");
You don't seem to be placing the incrementation of your num before writing it to the document. See the code below check the line between loops.
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (let i = 1; i <= 6; i++) {
//loop 2
num++;
for (let y = 0; y < i; y++) {
document.write(num);
}
document.write("<br>");
}
<p id="num"> </p>;

Jquery price increase by slab

i am working on some project and I'm facing some issue
actually i want price increase by slap like i am allowing customer to select guest for booking for e.g the main price of product is 100 and additional price of guest is 50 and limit of guest is 4 when customer select 5 guest then the main price should be add in total price after when customer select 6 guest then only add 50 price i am sharing some code but its not working properly.
main price = 100
addintion price = 50
Guest
Price
1
100
2
150
3
200
4
250
5
350 add main price again (100)
6
400
7
450
8
500
9
600 add main price again (100)
10
650
group_size = 4;
increased_group_size = 4;
total_guests = me.guests;
if(total_guests<=group_size){
increased_group_size -= group_size;
if(increased_group_size==0){
increased_group_size += group_size;
}
}
if(total_guests>increased_group_size){
main_price = main_price;
increased_group_size += group_size;
final_price += main_price;
}
else{
final_price1 = total_guests * me.addtional_price;
}
total += final_price1 + final_price + me.price;
I tried the above code but not working properly.
Divide the number of additional guests by the group size. For each group, add the difference between the main price and additional price.
function calculate_price(total_guests) {
let additional_guests = total_guests - 1;
let group_size = 4;
let additional_groups = Math.floor(additional_guests / group_size);
let main_price = 100;
let additional_price = 50;
let total_price = main_price + additional_guests * additional_price + additional_groups * (main_price - additional_price);
return total_price;
}
for (let guests = 1; guests <= 10; guests++) {
console.log(`Guests = ${guests} Price = ${calculate_price(guests)}`);
}
Essentially what you need to do is check whether the current number is divisible by your max number. Then add one number if it is, and another number if it isn't.
Here's a working example.
const guestNum = $(".guests-total");
const total = $(".total");
$(".button").on("click", (e) => {
let numMult = 1;
const num = parseInt(guestNum.text());
let curTotal = parseInt(total.text());
let testNum = num + 1;
if (e.target.classList[1] === "min") {
numMult = -1;
testNum = num;
if (num === 0) {
return;
}
}
while (testNum > 0) {
testNum = testNum - 5;
}
if (testNum !== 0) {
curTotal += numMult * 50;
guestNum.text(num + numMult * 1);
total.text(curTotal);
return;
}
curTotal += numMult * 100;
guestNum.text(num + numMult * 1);
total.text(curTotal);
return;
});
.wrapper {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 5vw;
gap: 2vw;
}
.row-one {
display: flex;
justify-content: center;
align-items: center;
gap: 3vw;
}
.icon-test {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div class="wrapper">
<div class="row-one">
<div class="button min">-</div>
<div class="guests-total">0</div>
<div class="button add">+</div>
</div>
<div class="row-two">
<div class="money-total">Total: $<span class="total">0</span></div>
</div>
</div>
</body>
</html>
Let's break this down.
Here we get the DOM elements for the number of guests and the sub-total of money.
const guestNum = $(".guests-total");
const total = $(".total");
Then we register an event listener for a click on the button to either add or subtract a guest.
$(".button").on("click", (e) => {
I set a variable called numMult that I will multiply all my sub-total numbers by to either subtract or add money (I'll explain that more later).
let numMult = 1;
Then I get the actual text contained in the DOM elements and convert those to integers so we can add or subtract from them.
const num = parseInt(guestNum.text());
let curTotal = parseInt(total.text());
Finally I make a new variable that will be used to test if the current number is a multiple of 5 or not.
let testNum = num + 1;
Here we check if the button that was clicked is the subtract button or the add button, if it's the subtract button then we will be multiplying all our numbers by -1 so that it subtracts from the subtotal instead of adds to it.
If the current number is 0 we return because there obviously can't be negative guests.
if (e.target.classList[1] === "min") {
numMult = -1;
testNum = num;
if (num === 0) {
return;
}
}
Here we subtract from the total number of guests until num is less than or equal to zero.
while (testNum > 0) {
testNum = testNum - 5;
}
If our test number doesn't come out as zero, we know that the number isn't 5 or divisible by 5, so we add or subtract 50.
if (testNum !== 0) {
curTotal += numMult * 50;
guestNum.text(num + numMult * 1);
total.text(curTotal);
return;
}
Otherwise, if our test number is 0, we know that the number of guests is either 5 or a multiple of 5, so we add 100.
curTotal += numMult * 100;
guestNum.text(num + numMult * 1);
total.text(curTotal);
return;
I hope this helps out.

Trying to fill 9 spaces with number between 1 and 2 with some rules

I'm trying to fill 9 boxes with numbers, these numbers could be number 1 or number 2, being that number 2 can only be 4 times and number 1 should fill the other 5 times left... i know it's a problem of simple logic but someway I can't reach my goal... look at the piece of code that I have...
<script type="text/javascript">
for (cicloTipo = 1; cicloTipo < 10; cicloTipo++) {
var tipo = Math.floor((Math.random() * 2) + 1);
document.write(tipo);
}
</script>
You can start with an array of the required values, then either shuffle the array or randomly select values from it. Some say Math.random isn't truely random, but it should be good enough.
The following uses splice to select values, so the loop iterates backwards since splicing shortens the source array each time.
function getRandoms(){
for (var seed=[1,1,1,1,1,2,2,2,2], result=[], i=seed.length; i; i--) {
result.push(seed.splice(Math.random() * i | 0, 1)[0]);
}
return result;
}
// Show randomness of result
(function() {
var s = new Array(30).fill('+');
var r;
for (var i=9; i; ){
document.getElementById(--i).textContent = s.join('');
}
var j = 300; // Number of runs
var delay = 20; // Default delay in ms
function display(lag) {
delay = lag || delay;
getRandoms().forEach(function(v, i, rand) {
var el = document.getElementById(i);
if (v == 1) {
el.textContent = el.textContent.slice(0,-1);
// If run out of "+", add some to every line
if (!el.textContent.length) {
for (var k=0; k < 9; k++) {
document.getElementById(k).textContent += '++++++++++';
}
}
} else {
el.textContent += '+';
}
if (i == 0) {
document.getElementById('msg').innerHTML = 'Remaining: ' + j +
'<br>' + 'Values: ' + rand.join('');
}
});
--j;
if (j > 0) {
setTimeout(display, delay);
}
}
display(50);
}());
// Single call
// console.log(getRandoms().join());
<span id="0"></span><br>
<span id="1"></span><br>
<span id="2"></span><br>
<span id="3"></span><br>
<span id="4"></span><br>
<span id="5"></span><br>
<span id="6"></span><br>
<span id="7"></span><br>
<span id="8"></span><br>
<span id="msg"></span>
For fun I've added a display of the distribution. Each line represents a value in the result array from 0 to 8 and starts with a set number of "+" symbols. Each time a 1 is in the related position, a "+" is removed. Each time a 2 is in the position, a "+" is added. Since there are more 1s than 2s, the lines slowly get shorter. When a line gets to zero length, 10 more "+" are added to every line.
The important part is that the lines stay about equivalent lengths and that the same lines aren't longest or shortest after each run. If you think you see a pattern emerging, it must be sustained for at least 100 runs to show a bias.
Here's a solution which ensures that no more than 4 2's are in the chain.
it means that the digits chain can contain from 0 2's to 4 2's and the rest is 1's
// 2s Counter
var c1 = c2 = 0;
for (var cicloTipo = 1; cicloTipo < 10; cicloTipo++) {
var tipo = Math.floor((Math.random() * 2) + 1);
// check if it's a 2 and 4 2s have been encountred
if (tipo == 2) {
if (c2 < 4) {
// increment counter
c2++;
} else {
tipo = 1;
c1++;
}
}
// check if it's a 1 and 5 1s have been encountred
else if (tipo == 1) {
if (c1 < 5) {
// increment counter
c1++;
} else {
tipo = 2;
c2++;
}
}
document.write(tipo);
}
it looks like your criteria forces 4 2's and 5 1's;
i fixed this code to fit this criteria but #Paul Rooney 's suggestion is the best.

Printing the next 10 even and odd numbers ( java-script)

1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
i am newbie to programming and trying to learn java-script myself, the above is the question i am trying to solve. i am confused, i am not sure how to make the code to write the next 10 odd even number (i am referring to the first question).also the previous 5 (referring to second question).. below is my starting attempt. i am stuck
function isEven {
var value = prompt("");
if (value % 2 == 0) {
for (var i = 2; i <= ; i = i + 2;)
document.write(i + "<br>");
}
}
isEven();
Answer 1:
if(number>=0){
for(i=2;i<21;i+=2){
console.log(number+i);
}
}
Answer 2:
for(i=2;i<11;i+=2){
if((number-i)>=0){
console.log(number-i);
}
}
1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
function function1() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.write(value + "<br>");
}
}
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
function function2() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 5; i = i + 1){
value = value - 2;
document.write(value + "<br>");
}
}
Just to clarify. You want to print both the previous 5 numbers and next 10 numbers of same 'evenness' for any given number?
In which case, you should do just that... You dont need to care if the number is even or odd, because the next/previous is always 2 away. (What you do when you cross 0 is up to you)
for (var i = 1; i <= 5; i++)
document.write((INPUT - (i*2)) + "<br>");
for (var i = 1; i <= 10; i++)
document.write((INPUT + (i*2)) + "<br>");
refer this woking demo. hope this will help to you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
Enter a number : <input type="number" id="num">
<button id="butp" class="chk">print previous five numbers</button>
|| <button id="butn" class="chk">print next ten numbers</button>
<ul id="print">
</ul>
<script type="text/javascript">
$(".chk").click(function(){
var the_id = $(this).attr('id');
//alert(the_id);
var theVal = parseInt($("#num").val());
if (the_id =="butp") //this means user asking for previous
{
if (theVal==0 || theVal < 10)
{
alert("cannot continue the operation, please enter a valid nubmer to continue");
}
else
{
for (var i=1;i<6;i++)
{
newVal = theVal - (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
else // this means user asking for next
{
for (var i = 1;i<11;i++)
{
if (theVal==0)
{
alert("please enter a valid number to continue");
}
else
{
newVal = theVal + (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
});
$("#num").on('change keyup keydown', function(){
theVal = $(this).val();
if (theVal == "")
{
$("#print li").css({"display":"none"})
}
})
</script>
</body>
</html>
function evenOdd(value) {
if(value%2==0){
console.log(`it's and even number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}else{
console.log(`it's and odd number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}
}
evenOdd(13)

PESEL checksum validation(Javascript/HTML)

Im a student currently studying from home and im seriously stuck on a Checksum problem. The script is supposed to validate the PESEL(Polish equivilant of a social security number i think), Anyway the checksum works as follows for
PESEL: 70051012347
PESEL:7,0,0,5,1,0,1,2,3,4 (7)
(Multiply each Pesel number by its corresponding check number)
CHECK:1,3,7,9,1,3,7,9,1,3
(Sum Each number)
SUM: + 7,0,0,45,1,0,7,18,3,12 =93
MOD: 93 MOD 10 = 3
10 - 3 = 7(last digit of pesel)
Where the MOD 10 doesn't equal 0, the result of sum%10 is subtracted from 10 and then matched with the final digit in the original number, if they match its good, if not its bad. All i need to have is a good or bad result.
I'm pretty sure I have all of this fine in my code and there's a simple solution i just cant see it. Any help at all would be massively appreciated.
<html>
<head>
<meta charset="utf-8">
<title>Pesel Checker</title>
<script type="text/javascript">
function peselgood(y)
{
//sample PESEL's
//type 1
//70051012347
//02070803628
//07020803628
//type 2
//83102570819
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//hold original number
var a = parseInt(y);
//First 10 digits without check number and convert to array
y = y.substring(0,9);
y = parseInt(y);
var arr1 = new Array(10);
arr1 = y;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * arr1[i];
}
sum = sum%10;
if (sum !== 0)
{
sum = 10-sum;
if(sum != a[10])
{
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
function checkpesel()
{
num = document.getElementById("peselfield").value
if (peselgood(num))
{
document.getElementById("peselfield").style.background="#00ff00";
}
else
{
document.getElementById("peselfield").style.background="#ff6666";
}
}
</script>
</head>
<body>
<div>
Check Sum Template
<br/><br/>
<form name="form">
PESEL:
<input type="text" id="peselfield" value="70051012347" /> <button type="button" onclick="checkpesel()">Check</button>
<br/><br/>
</form>
</div>
<br/><br/>
</body>
</html>
You have made a couple of mistakes. If you step through your code using a JavaScript debugger, you will find out exactly what goes wrong. The most important fact is, that you don't have to convert a string to an array of integers. JavaScript automatically understands when to convert a character to an integer.
This is my solution:
function peselgood(y)
{
if (y.length == 11)
{
var arr = [1,3,7,9,1,3,7,9,1,3];
var sum = 0;
//muliply pesel digits by checksum digits
for (var i = 0; i < 10; i++)
{
sum += arr[i] * y[i];
}
sum = sum%10 == 0 ? 0 : 10-sum%10;
return sum == y[10];
}
else
{
return false;
}
}
function checksum(p) { let i, s = +p[ i = 10 ]; while( i-- ) s += "1379"[ i % 4 ] * p[i]; return ! ( s % 10 ); }
<input id="pesel" placeholder="PESEL" autofocus>
<input type="button" value="check" onclick="alert( checksum(pesel.value) ? 'Ok' : 'Bad' )">

Categories