Creating a simple multiplication table - javascript

Here's the code i've written, which is included in a HTML document:
<script type="text/javascript">
var cipars = 10;
var i =0;
document.write('<table border="1" cellspacing="0" id="Tabula">');
for (i=1; i<10; i++) {
for (j=1; j<10; j++) {
document.write("<tr><td>" + i + " x " + j + " = " + j*i + "</td></tr>");
}
}
document.write("</table>");
</script>
What my code does now is that makes a multiplication column more than a table. Can anyone give me a hint how to make it... More like a table? I've explained the problem as good as I can.

Change it to this:
js
var cipars = 10;
var i =0;
document.write('<table border="1" cellspacing="0" id="Tabula">');
for (i=1; i<10; i++) {
document.write("<tr>");
for (j=1; j<10; j++) {
document.write("<td>" + i + " x " + j + " = " + j*i + "</td>");
}
document.write("</tr>");
}
document.write("</table>");

Related

turning a for loop into while loop

what is the best way to convert this into a while loop?
<html>
<head>
<script type="text/javascript">
<!--
function GetGrades() {
var grades = [];
var grade;
var sum = 0;
for(i=0; i<5; i++) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
}
for(i=0; i<5; i++) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
}
var avg = sum/5.0;
document.write("</br>Grade: " + avg + "</br>");
}
//-->
</script>
</head>
<body onload="GetGrades()">
</body>
</html>
I have ignorantly tried to simply declare the variable i as sero and change the for to while.
while(i<5) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
i++;
}
while(i<5) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
i++;
}

Calculating average from array and recieving a NaN error

I'm having issues with trying to convert objects from a string array into integers. I've used parseInt and parseFloat but none of it is working. Do I need to maybe structure the array declaration differently or the prompt?
Thanks guys
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=1; i<=10; i++){
scores[i] = prompt("Enter score " + i);
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(sum + scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
You're using the for loop for prompt from 1 to 10, but calculating the sum in Average looping 0 to 9. The scores[0] is undefined as it is never assigned a value in the prompt loop whcih results to NaN when added to other numbers. Also you're adding sum in parseInt which is wrong.
Here is the fixed code :
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Hope this helps !
following line is wrong in your code :
scores[i] = prompt("Enter score " + i);
I have written a small piece of javascript code which will do the average calculation. What it's doing is, getting the number in a variable from the prompt and pushing it into the array.
function calAverage(){
var sum = 0;
for (var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
return avg;
}
var scores = [];
for (var i=1; i<=10; i++){
var number = prompt("Enter score :");
scores.push(parseInt(number));
}
console.log(scores);
var average = calAverage(scores);
console.log("Average = " + average);
There are a few issues here:
scores[i] = prompt("Enter score " + i);, I would exchange this for scores.push(parseInt(prompt("Enter score " + i)));, as prompt returns a string, upon which most operations will fail and return NaN. Setting scores[i] = does work, but can be messy if you try to scale it up.
sum += parseInt(sum + scores[i]);, you have already got the +=, and as such the extra sum + ... effectively translates to sum = (2 * sum) + scores[i], meaning we can reduce this to sum += scores[i];
The complete code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores.push(parseInt(prompt("Enter score " + i)));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Here's the working code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<=9; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + (i + 1) + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i], 10);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Thanks for the help, Andreas.
I did some modification in your code and also applied a check if user enter any value other than a number.
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = parseFloat(prompt("Enter score " + (i+1)));
if(isNaN(scores[i])){
scores[i]=0;
}
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
Average();
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
<div id="average"></div>

How to sum Total JSON Results?

i have this script to take data from JSON Results, also this script filter results by ID
$(document).ready(function () {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
}
}
});
});
Also i have this script sor SUM Of column with class vkupno1, but not understand the results from cell.
$(document).ready(function () {
colSum();
});
function colSum() {
var sum = 0;
$(".vkupno1").each(function () {
sum += parseFloat($(this).text());
});
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
}
How to sum (json[i].vkupnot)-value or cell classed "vkupno1"
here is JSON Results:
[{"smetki":null,"trId":1,"skID":1,"Artikal":"gdfgsdgfdg","kol":4.00,"cena":4.00,"vkupnot":16.00},{"smetki":null,"trId":4,"skID":4,"Artikal":"kjhkjhkjhk","kol":7.00,"cena":7.00,"vkupnot":47.00},{"smetki":null,"trId":5,"skID":4,"Artikal":"lkjlkjlk","kol":8.00,"cena":8.00,"vkupnot":64.00},{"smetki":null,"trId":6,"skID":5,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":7,"skID":6,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":8,"skID":7,"Artikal":"gagaggag","kol":5.00,"cena":55.00,"vkupnot":275.00},{"smetki":null,"trId":9,"skID":7,"Artikal":"ggg","kol":4.00,"cena":65.00,"vkupnot":260.00}]
You can add the values from response itself without reading from DOM.
Try this
$(document).ready(function() {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function(json) {
var tr;
var sum = 0; //initialising sum
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
sum += parseFloat(json[i].vkupnot); //adding directly from the response
}
}
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
});
});
And you need to wait for the response before reading the dynamically created DOM elements.

How to remove from list with onclick function?

I am trying to create a function that will allow me to remove an item from the shopping cart of the site I'm working on. I want the last image when clicked to remove that specific item from the list and immediately show it. I don't want to have to refresh the page to see the update. I have tried everything I can find, and tried to kind of reverse engineer my addtocart one from before but I just can't get it. Any help is appreciated!
var x = JSON.parse(sessionStorage.getItem('shoppingList'));
document.write('<table align="center" >');
document.write('<tr>');
document.write('<th>' + " " + '</th>');
document.write('<th>' + "Product" + '</th>');
document.write('<th>' + "Price" + '</th>');
document.write('<th>' + "Quantity" + '</th>');
document.write('<th>' + "Remove" + '</th>');
document.write('</tr>');
for (var i = 0; i < x.length; i++){
document.write('<tr>');
for(var j = 0; j < 1; j++){
document.write('<td align="center">');
document.write('<img src="');
document.write(x[i].itemImageSrc);
document.writeln('"style="height:100px; width:150px;"/>');
document.write('</td>');
document.writeln('<td align="center">' + x[i].itemDescription + '</td>');
document.writeln('<td align="center">' + x[i].itemPrice + '</td>');
document.write('<td align="center">' + "1" + '</td>');
document.write('<td align="center">');
document.write('<img id="can_'+i+'" onclick="removeItem(i)" src="');
document.write("./images/Icons/garbagecan.png");
document.writeln('"style="height:25px; width:20px;"/>');
document.write('</td>');
}
document.write('</tr>');
}
document.write('</table>');
function removeItem(i) {
var list = JSON.parse(sessionStorage.getItem("shoppingList"));
list.pop(document.getElementById("can_'+i+'"));
//x[i] = null;
}
TheChetan was kind of right. What I need to do was add
sessionStorage.setItem("shoppingList", JSON.stringify(list));
window.location.href=window.location.href
to the end of my removeItem function

Change text of a button in jquery

i have a board that contains 9 small boards and each small board contains 9 cells (Ultimate TicTacToe).
i'm trying to use the click function and print "x" on the clicked button but it doesnt change the text of the button and i dont have an idea why.
please help me.
here is the code:
<script>
var bigTable = "<table align='center' value='bigBoard' border='0' cellpadding='1' cellspacing='1'\><tbody>";
for (var k = 0; k < 9; k++)
{
if (k % 3 === 0)
{
bigTable += "<tr>";
}
bigTable += "<td>";
var mytable = "<table value='smallBoard'+k border='1' cellpadding='1' cellspacing='1'><tbody><tr>";
for (var j = 0; j < 3; j++)
{
for (var i = 0; i < 3; i++)
{
var position = +k + "," + j + "," + i;
mytable += "<td><button class='a' id=" + position + " type='submit' name=" + position + "></button</td>";
}
mytable += "</tr><tr>";
}
mytable += "</tr></tbody></table>";
bigTable += mytable + "</td>";
if (k % 3 === 2)
{
bigTable += "</tr>";
}
}
bigTable += "</tbody></table>";
document.write(bigTable);
</script>
<script>
$(document).ready(function() {
$(".a").click(function() {
var buttonPressed = $(this).attr("id");
jQuery.ajax({
data:buttonPressed,
url:"board",
success: function(responseText){
//alert("acac" + buttonPressed);
$("#" + buttonPressed).text(responseText);
}
});
});
});
</script>
This is what you are doing wrong, change this:
var position = +k + "," + j + "," + i;
to something like,
var position = +k + "-" + j + "-" + i;
Change the type of button from submit to button because you are calling Ajax request, not submitting the form.
I ran this jsfiddle and it works fine
Try it
http://jsfiddle.net/P8wrb/1/
Just declare a variable for your clicked button and then set the .text for it by reference
$(".a").click(function() {
var that = $(this);
....
that.text('X');
}

Categories