How to print different value for each table row using javascript - javascript

I just want to create a multiplication table using Javascript but I don't want each row to have the same result. I will picture that table I want to be created for my work
In this code, the program will print 9 times
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = 1; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
I already make a table for multiplication but I don't want to make all print 10 times. I want to make different for each table cell
I want to make like this picture and I'm new with JavaScript

var times = 1;
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > (9 - times); i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
times++;
}

You can simply add this to the second loop for (i = 1; i <= a; i++) that way you'll achieve what you want.
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 5px">')
for (i = 1; i <= a; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}

The simple answer is replace this line for (i=1; i<=9; i++) { with this: for (i=a; i<=9; i++) {
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = a; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}

For having the exact same thing as you posted in your picture, this code do the job :
document.write("<table>");
for (a = 9; a > 0; a--) {
document.write("<tr>")
for (i = 9; i > a - 1; i--) {
document.write('<td>' + a + ' x ' + i + ' = ' + a * i + '</td>');
}
document.write('</tr>')
}
document.write("</table>")
Note the use of decrementing loop to match the order of your picture and the usage of the table

Related

How do I add numbers following a string in JavaScript

I want to console.log a string but also add numbers inside of it. For example if I use the following code:
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log("#" + i + 1 + " Heads");
} else {
console.log("#" + i + 1 + " Tails");
}
}
Since what I want to console.log starts with a string I can't seem to add numbers right after it. They become strings.
I want to get:
"#2 Tails"
But I get:
"#11 Tails"
How do I get "#2 Tails" instead of "#11 Tails"?
You need to wrap your addition in brackets.
console.log("#" + (i + 1) + " Heads");
or use string interpolation
console.log(`#${i+1} Heads`);
You can first sum up the value of i and 1 to num before the concatination
1)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
const num = i + 1;
if (coinFlip === 1) {
console.log("#" + num + " Heads");
} else {
console.log("#" + num + " Tails");
}
}
2)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log("#" + (i + 1) + " Heads");
} else {
console.log("#" + (i + 1) + " Tails");
}
}
3)
for (let i = 0; i < 5; i++) {
coinFlip = Math.round(Math.random());
if (coinFlip === 1) {
console.log(`#${i + 1} Heads`);
} else {
console.log(`#${i + 1} Tails`);
}
}

Javascript loop through date/times in vali increments

I've trying to build out a table from a start time until the end of day in defined increments.
eg: if the user selects 15 minute increment starting from 8:10am, the times goes
8:10,8:25,8:40,8:55,9:10...
My current code does not correct work out we've changed to the next hour and then start the offset again, eg i get:
815,830,845,905,935,1025,1125,1225,1325...
Here is a JSFiddle
https://jsfiddle.net/inboxdesign/c8f2dhng/13/
Here is the code I have so far;
// from select:
let $first_hour = 8;
let $first_minute = 10;
let day_count = 1; // don't worry about this;
let duration = 15; // increment
var offset = 0;
var current_time = parseInt($first_hour + $first_minute);
for (var i = 0; i < 120; i++) {
if (current_time < 2400) {
var time_string = ('' + current_time);
var time_minutes = parseInt(time_string.substring(time_string.length - 2));
if (time_minutes < 60) {
// offset = 0;
times += '<tr>';
for (var d = 1; d <= day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_string.substring(time_string.length - 2) + ' offset: ' + offset +'</td>';
}
times += '</tr>';
} else {
offset = (time_minutes - 60);
// times += '<tr>';
// times += '<td>o:' + offset + ' tm: ' + time_minutes + '</td>';
// time_minutes = offset;
// times += '</td>';
}
}
console.log('current_time: ' + current_time);
current_time = parseInt(current_time + duration + offset);
In this line your else offset has to be reset to 0
for (var d = 1; d <= SP.new_conference.day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_minutes + ' offset: ' + offset +'</td>';
}
// times += '</tr>';
} else {
offset = 0;
and then your current time and offset should look like this
current_time = parseInt(current_time + SP.new_conference.duration );
offset+=SP.new_conference.duration
I have fixed this issues in the jsfiddle if you want to have a look

Comparing inner loop variable with outer loop variable- Javascript

I have created a code for a multiplication table and I was advised the following:
"You could compare the inner loop variable with the outer loop value... e.g., i > a"
What is meant by this? Is there something that I'm not doing correct?
Thanks in Advance!!
<!DOCTYPE html>
<html>
<head>
<title> Java Script </title>
<h1> 6.2 Task JavaScript </h1>
<script>
var times = 1;
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > (9 - times); i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
times++;
}
</script>
</head>
<body>
</body>
</html>
The variable times is not needed, and instead of using 9 - times you can use a - 1 because that always gives the same value.
Demo:
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > a - 1; i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
}
Alternatively you can use i >= a instead of i > a - 1 and the condition for i > 0 is superfluous:
for (a = 9; a > 0; a--) {
for (i = 9; i >= a; i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
}
U can shorten the code a little if you compare the inner varibale a against i instead of using a second variable times:
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > a - 1; i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
}

Thumbnails From External Sources Are Not Appearing In Random Posts Widget

Here is the jsfiddle for my question.
http://jsfiddle.net/jaribhai/wncwqerj/1/
This is the code.
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("summary" in entry[i]) ? (entry[i].summary.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for(var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
This is the demo of random posts widget from blogger. It is showing thumbnails from only those posts where images are linked from blogger but its not showing thumbnails for those images which are linked from external sources.
What can I do so that images from external hosts also appear in the thumbnails.
As the image is hosted externally , it won't be present in the media$thumbnail field of the feed. We will have to parse the HTML content of the post to extract the URL of the image. Two changes need to be done to make this work -
Firstly switch from the summary feed to default feed URL. This is necessary for getting the HTML content of the post (summary feed only contains the limited summary text of the post not the full HTML). Change every instance of
/feeds/posts/summary?alt=json-in-script
to
/feeds/posts/default?alt=json-in-script
Secondly change the condition for finding the image in the post from
img = ("media$thumbnail" in entry[i]) ? entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c") : noImageUrl;
to
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
Refer to the working example below -
// Feed configuration
var homePage = 'http://video-testing-tahir.blogspot.com',
maxResults = 4,
summaryLength = 170,
noImageUrl = 'http://3.bp.blogspot.com/-vpCFysMEZys/UOEhSGjkfnI/AAAAAAAAFwY/h1wuA5kfEhg/s72-c/grey.png',
containerId = 'random-post-container';
// Function to generate random number limited from `min` to `max`
// Used to create a valid and safe random feed `start-index`
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to shuffle arrays
// Used to randomize order of the generated JSON feed
function shuffleArray(arr) {
var i = arr.length,
j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
// Get a random start index
function createRandomPostsStartIndex(json) {
var startIndex = getRandomInt(1, (json.feed.openSearch$totalResults.$t - maxResults));
if (window.console && window.console.log) console.log('Get the post feed start from ' + startIndex + ' until ' + (startIndex + maxResults));
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/default?alt=json-in-script&orderby=updated&start-index=' + startIndex + '&max-results=' + maxResults + '&callback=randomPosts');
}
// Widget's main function
function randomPosts(json) {
var link, summary, img,
ct = document.getElementById(containerId),
entry = shuffleArray(json.feed.entry),
skeleton = "<ul>";
for (var i = 0, len = entry.length; i < len; i++) {
summary = ("content" in entry[i]) ? (entry[i].content.$t.replace(/<.*?>/g, "")).substring(0, summaryLength) + '…' : "";
if ("media$thumbnail" in entry[i]) {
img = entry[i].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s72-c");
} else if (entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
img = entry[i].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
img = noImageUrl;
}
for (var j = 0, jen = entry[i].link.length; j < jen; j++) {
link = (entry[i].link[j].rel == "alternate") ? entry[i].link[j].href : '#';
}
skeleton += '<li>';
skeleton += '<img src="' + img + '" alt="" width="72" height="72">';
skeleton += '' + entry[i].title.$t + '<br>';
skeleton += '<span>' + summary + '</span>';
// Show all post labels ...
skeleton += ' <small>';
var tags = entry[i].category,
labels = [];
for (var z = 0, zen = tags.length; z < zen; ++z) {
labels.push('' + tags[z].term + '');
}
skeleton += labels.join(', ');
skeleton += '</small>';
skeleton += '<span class="clear"></span></li>';
}
ct.innerHTML = skeleton + '</ul>';
}
// document .write('<scr' + 'ipt src="' + homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex"></scr' + 'ipt>');
add_script(homePage + '/feeds/posts/summary?alt=json-in-script&max-results=0&callback=createRandomPostsStartIndex');
/**
* `document[dot]write` is disallowed in JSFiddle envioriment and might break your fiddle.
*/
function add_script(url) {
var s = document.createElement('script');
s.src = url;
document.getElementsByTagName('head')[0].appendChild(s);
}
body {
margin: 0;
padding: 50px;
background-color: white;
font: normal normal 11px/1.4 Arial, Sans-Serif;
color: black;
}
#random-post-container {
width: 400px
}
#random-post-container ul,
#random-post-container li {
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
}
#random-post-container img {
display: block;
float: left;
border: 1px solid;
margin: 2px 7px 5px 0;
}
#random-post-container a {
font-weight: bold;
font-size: 110%;
}
#rancom-post-container .clear {
display: block;
clear: both;
}
<h2>Random Post</h2>
<div id='random-post-container'>Memuat…</div>

print time of javascript using loop

I stuck until here, I got infinite loop when I proceed. Below code is a half way, how to print from 1:00 AM to 12: AM.
http://jsfiddle.net/sychhLya/
JS
$(function () {
for (i = 0; i < 12; i++) {
var time = '<p>' + i + ':00 AM</p>';
$('.holder').append(time);
}
});
Here is a solution using the Date class in Javascript:
$(function () {
var x = new Date("March 3, 2015 01:00");
for (i = 0; i < 12; i++) {
$('.holder').append(x.getHours() + ":" + x.getMinutes() + x.getSeconds() + "AM<br/>");
x.setHours(x.getHours()+1);
console.log(x);
}
});
JSFiddle: http://jsfiddle.net/sychhLya/3/
Is this what you want?
$(function() {
for (i = 1; i <= 12; i++) {
var time = '<p>' + i + ':00 AM</p>';
$('.holder').append(time);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="holder"></p>
Or this?
$(function() {
for (i = 1; i <= 12; i++) {
for (j = 0; j < 60; j++) {
j = ("0" + j).slice(-2);
var time = '<p>' + i + ':' + j + ' AM</p>';
$('.holder').append(time);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="holder"></p>

Categories