I'm having issues with displaying my for loop on my page. There is a button which upon the click prompts the user to enter a number then display the iterations of said number through a for loop. I've looked at similar questions that have been asked on here but seem to still be running into a problem.
<!doctype hmtl>
<html>
<head></head>
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<script>
function getNumber() {
var i;
var num;
var n = prompt("Please enter a number");
for(i = 0; i < n.length; i++){
num += n[i];
document.getElementById("demo").innerHTML += num + " ";
}
}
</script>
</body>
</html>
You were trying to get the length property of the users inputted value instead of the value directly.
Also, there are several unnecessary bits in your code and several bad practices that adversely affect performance.
// Get a reference to the HTML (DOM - Document Object Model) elements that
// you will need access to at this level of scope
var btn = document.getElementById("btn");
// Don't set up event handling code in the HTML (a.k.a. inline event handling) as it
// makes the HTML harder to read (two languages on a single line), it doesn't follow
// the standard for event handling, and it causes anonymous Global JavaScript functions
// to be made as wrappers around the HTML attribute values. Instead, do it in JavaScript
// like this:
btn.addEventListener("click", getNumber);
function getNumber() {
// Just scan for the element once, not each time the loop iterates
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = "";
for(var i = 0; i < n; i++){
// NEVER alter an HTML (DOM) element within a loop as performance suffers
// because the browser must recreate the entire DOM structure.
// Instead, set up a variable that holds the results
output += " " + i;
}
// Once loop is done, update element with the variable. But, this way,
// you are doing it just once, instead of each time the loop iterates.
// Also, if the new content does not include HTML, then use textContent
// instead of innerHTML as it lets the browser know that the data does
// not have to be parsed, which results in a quicker update.
el.textContent = output;
}
<button id="btn">Click!</button>
<p id="demo"></p>
It should be i < n not i < n.length. Because what you are doing is looping as much times as there is characters in your variable n (which is a string by the way). So if the user types 9 only one number is printed because "9".length is 1 and there is only one iteration between 0 and 1 (excluded). Try this:
function getNumber() {
var num = 0; // this should be initialized
var n = prompt("Please enter a number");
for(var i = 0; i < n; i++){
num += i; // add i
document.getElementById("demo").innerHTML += num + " ";
}
}
Not Sure what exactly you are trying, but if you want repeat for loop till the user entered input, you can do it as following
check this snippet
function getNumber() {
var i;
var num;
var n = prompt("Please enter a number");
for (i = 0; i < n; i++) {
document.getElementById("demo").innerHTML += i + " ";
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
Hope it helps
The problem lies in n.length part. Imagine user provides number "10". The length property for number 10 is 2 so the code inside the loop is executed 2 times instead of 10 times.
<html>
<head>
</head>
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<script>
function getNumber() {
var i;
var num;
var n = parseInt(prompt("Please enter a number"));
for(i = 1; i <= n; i++){
document.getElementById("demo").innerHTML += " " + i;
}
}
</script>
</body>
</html>
Related
I wrote JavaScript code which tells you the average of numbers. You enter the numbers by pressing the add button. The added numbers will be shown on the screen. If you don't enter any number, A text "empty string" will be shown and if you enter numbers this message will be not shown and the average of entered numbers will be shown.
But the problem is that, even after entering the numbers still the text "empty string" is shown. And I can't find out why. When I wrote this code without giving user the ability to enter numbers and provide numbers by myself. The same code was working correctly and was showing average but when I added the function to enter numbers... the "average code" start troubling.
Code:
<body>
<h2>Averge Function</h2>
<p>Press the button below to add numbers in the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
var grades = [];
function addNum() {
var grade = prompt("Add a number");
grades[grades.length] = grade;
document.getElementById("numInArray"). innerHTML =
"Numbers in array are: " + grades;
}
var sum = 0;
if (grades.length > 0) {
for (index = 0; index < grades.length; index++) {
sum += grades[index];
}
document.getElementById("average").innerHTML = sum/grades.length;
}
else {
document.getElementById("average").innerHTML = "Empty string";
}
</script>
</body>
Among things you should look into
When code is executed (function declaration, vs execution
The order of things
Scopes
An example of how you could rewrite your code with some comments on what has been changed:
<body>
<h2>Averge Function</h2>
<p>
Press the button below to add numbers in the array:<br />
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
// Initiate application by declaring variables that should be re-used for everytime addNum will be executed
var grades = [];
var sum = 0;
// Initiate the DOM, changed "Empty string" to "Empty array" while I am nitpicking anyways ;)
document.getElementById("average").innerHTML = "Empty array";
// Function that runs only when user creates an input
function addNum() {
var grade = prompt("Add a number");
// Push is a simple way to add something to an array (in this case grade to your grades array)
grades.push(grade);
// Removed that for loop for there was no use....
// Add the grade value (still available from the prompt above) to your sum variable and force it to be a number with parseInt! (If you don't force the prompt value to be a number javascript will take your initial sum 0 and add a string of the user input e.g. "5", javascript will convert that into "05", add another 5 and javascript will store "055", giving some unexpected results)
sum += parseInt(grade);
// Update the DOM
document.getElementById("numInArray").innerHTML = "Numbers in array are: " + grades;
document.getElementById("average").innerHTML = sum / grades.length;
}
</script>
</body>
Final tip from me would be:
First "design" your application in pseudo code, trying to explain what will need to happen in detail in every step. In this case steps I would identify would be:
Initialization of the app
Updates after user input
When you are calling the addNum() function, you are simply adding more elements to your array, and not much else. What you need to do is, add the numbers in addNum() again and putting that in the HTML. I've refactored your code. A few pointers:
Avoid using var, and instead use const and let, as they help you manage scope of your variable more easily.
To add more items to an array use, Array.push().
I've wrapped your static string Numbers in array are: in a <p> element that in turn has the <p> element to display your numbers.
If try to add a string and number in JavaScript, they will simply be concatenated together. Use parseInt() to get the integer value of a variable. This returns NaN when the the first non-whitespace character cannot be converted to a number.
const grades = [];
function addNum() {
const grade = prompt("Add a number");
if(grade.length > 0){
grades.push(grade);
}
document.getElementById("numInArray").textContent = grades;
document.getElementById("average").textContent = findSum();
}
function findSum() {
let sum = 0;
for (index = 0; index < grades.length; index++) {
sum += parseInt(grades[index]);
}
return sum > 0 ? sum / grades.length : "Empty string";
}
<h2>Averge Function</h2>
<p>Press the button below to add numbers in the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p>Numbers in array are: <span id="numInArray"></span></p>
<p id="average"></p>
I am running a function that populates several paragraph tags on a webpage with the days of the week. The function takes an array of days which is populated based on the current day (i.e. if today is Thursday, get the next 7 days in order).
My problem is that for some reason, I am unable to populate these tags. I have checked to make sure that the array is getting populated and the list is being iterated through. While both of these are true, none of the Inner HTML of the tags are being changed.
HTML:
<p class="mb-1" id="forecastDay1" runat="server">Day</p>
<p class="mb-1" id="forecastDay2" runat="server">Day</p>
JavaScript Function:
function populatePage(arry) {
var i;
for (i = 0; i < arry.length - 1; i++) {
var id = "forecastDay" + i.toString();
document.getElementById(id).innerHTML = arry[i].toString();
}
}
I have also tried it this way:
document.getElementById("forecastDay" + i.toString()).innerHTML = arry[i].toString();
You do not need toString in JavaScript.
Also, arrays start at 0, while your elements start at 1. You have to compensate that difference.
function populatePage(arry) {
var i;
for (i = 0; i < arry.length; i++) {
var id = "forecastDay" + (i + 1);
document.getElementById(id).innerHTML = arry[i];
}
}
// Test it
populatePage(["Day 1", "Day 2"]);
<p class="mb-1" id="forecastDay1" runat="server">Day</p>
<p class="mb-1" id="forecastDay2" runat="server">Day</p>
There are a few things wrong with your code:
The first value of i is 0. Since there is not element #forecastDay0, getElementById will return null. Trying to access innerHTML of null will throw an error, thus breaking the for loop and every thing after it. You should check your console when something doesn't work, it's a great way to debug.
The check for the for loop should be i < arry.length not i < arry.length - 1.
You don't need any of the toString calls.
That being said, here is how it should be:
function populatePage(arry) {
var i;
for (i = 0; i < arry.length; i++) {
var id = "forecastDay" + (i + 1); // i + 1 instead of just i. The casting to strings is done automatically
document.getElementById(id).textContent = arry[i]; // use textContent as there isn't really any HTML
}
}
I have a hopefully pretty easy problem. I'm trying to create a JS function on my app where there's a number in HTML and every time it is clicked, another number is subtracted from it and the result displays.
(So far this much works.)
Then the action should be repeatable so the number keeps getting smaller.
(This part doesn't work yet.)
Finally, there's a reset button that, when clicked, resets the original number to a random number.
(The random number is found correctly, but when you click to subtract it subtracts from the original number, not from the randomly-chosen replacement number.)
Here's a partially-working JSFiddle
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
var n = n - s;
document.getElementById("countdownNumber").onclick = function updateNumber(){
this.innerHTML = n;
}
document.getElementById("resetCountdown").onclick = function resetCountdown(){
var n = Math.floor(Math.random() * 500) + 200;
document.getElementById("countdownNumber").innerHTML = n;
}
<h3>Count down from the number you see in incriments of <span class="incrimentOfNumber" id="incrimentOfNumber">7</span>.
<br />Tap the number to see the correct answer.
<br />Repeat as needed.
</h3>
<div class="countdownNumber">
<h1 id="countdownNumber">284</h1>
</div>
<div class="btn" id="resetCountdown">Reset</div>
Can anyone (1) double check what I've done to make sure I'm not doing things in a stupid way and (2) help me figure out how to get the repeatable action functioning?
The issue is you are calculating value of n only once, it should be calculated on every click thus change you countdown click function to:
document.getElementById("countdownNumber").onclick = function updateNumber(){
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
n = n - s;
this.innerHTML = n;
}
Here is a working demo:
https://jsfiddle.net/m3q8fn2x/
If you are still struggling with this ,then consider the fact that when you declare a variable inside an event function its starting value is always the same , when the event is triggered. So consider this fact and declare variables outside the event function's scope.
const togglerBtn = document.getElementById("togglerBtn");
let temp = false;
togglerBtn.addEventListener("click", () => {
// alert();
if (!temp) {
togglerDiv.style.transform = "translateY(48px)";
return (temp = true);
} else if (temp) {
togglerDiv.style.transform = "translateY(-500px)";
return (temp = false);
}
});
Here is your working code:
You need to put the n = n - s part into the update number function so its called each time you click.
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
document.getElementById("countdownNumber").onclick = function updateNumber() {
n = n - s;
this.innerHTML = n;
}
document.getElementById("resetCountdown").onclick = function resetCountdown(){
n = Math.floor(Math.random() * 500) + 200;
document.getElementById("countdownNumber").innerHTML = n;
}
<h3>Count down from the number you see in incriments of <span class="incrimentOfNumber" id="incrimentOfNumber">7</span>.
<br />Tap the number to see the correct answer.
<br />Repeat as needed.
</h3>
<div class="countdownNumber">
<h1 id="countdownNumber">284</h1>
</div>
<div class="btn" id="resetCountdown">Reset</div>
I have some file contents I'd like to pass on to my server using a javascript function. In the file, there are many empty lines, or those which contain useless text. So far I read every line in as a string stored in an array.
How do I then loop through that content skipping multiple lines such as lines 24,25, 36, 42, 125 etc. Can I put these element id's into an array and tell my for loop to run on every element except these?
Thanks
you can't tell your for loop to iterate all, but skip certain elements. it will basically just count in any direction (simplified) until a certain critera has been met.
you can however put an if inside your loop to check for certain conditions, and chose to do nothing, if the condition is met. e.g.:
(pseudo code below, beware of typing errors)
for(var line=0; line < fileContents.length; line++) {
if(isUselessLine(line)) {
continue;
}
// process that line
}
the continue keyword basically tells the for loop to "jump over" the rest of the current iteration and continue with the next value.
The isUselessLine function is something you'll have to implement yourself, in a way, that it returns true, if the line with the given linenumber is useless for you.
You can try this its not much elegent but will suerly do the trick
<html>
<body>
<p>A loop which will skip the step where i = 3,4,6,9.</p>
<p id="demo"></p>
<script>
var text = "";
var num = [3,4,6,9];
var i;
for (i = 0; i < 10; i++) {
var a = num.indexOf(i);
if (a>=0) {
continue;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
You could use something like this
var i = 0, len = array1.length;
for (; i < len; i++) {
if (i == 24 || i == 25) {
array1.splice(i, 1);
}
}
Or you can have an another array variable which got all the items that need to be removed from array1
Another method:
var lines = fileContents.match(/[^\r\n]+/g).filter(function(str,index,arr){
return !(str=="") && uselessLines.indexOf(index+1)<0;
});
If you have many indices to skip, and this depends on the elements of the array, you could write a function that returns the number of elements to skip over for each index in that array (or returns 1, if no skipping required):
for ( let i = 0;
i < array.length;
i += calcNumberOfIndicesToSkip( array, i )){
// do stuff to the elements that aren't
// automatically skipped
}
function calcNumberOfIndicesToSkip( array, i ){
// logic to determine number of elements to skip
// (this may be irregular)
return numberOfElementsToSkip ;
}
In your case:
// skip the next index (i+1)?
for ( let i=0; i<array.length; i+=skipThisIndex(i+1) ){
// do stuff
}
function skipThisIndex(i){
const indicesToSkip = [ 24, 25, 36, 42, 125 ];
return 1 + indicesToSkip.includes(i);
}
// returns 1 if i is not within indicesToSkip
// (there will be no skipping)
// => (equivalent to i++; normal iteration)
// or returns 1 + true (ie: 2) if i is in indicesToSkip
// => (index will be skipped)
I have an assignment in school where we should grab a text string taken from a promt and then let an alert print the text string 10 times. But we have to use a for-loop. But I can't seem to get it to work even though I read all the pages covering this.
function buttonAction7() {
var someMsg = prompt("Write something");
for(var i = 0; i < 10; i++){
someMsg+someMsg;
}
alert(someMsg);
}
The statement:
someMsg+someMsg;
Doesn't actually do anything, it just returns a logical value. You'll probably want to assign this value to something, such as:
someMsg = someMsg + someMsg; // Notice assignment operator, we're now actually modifying the value of someMsg
If you wanted to build a string with the message 10 times, you'd probably want something more like:
var someMsg = prompt("Write something");
var msg = '';
for(var i = 0; i < 10; i++)
{
msg += someMsg + '\n'; // Add a line break after each iteration
}
window.alert(msg);
If i understand what you're asking, you want the alert to display the string 10 times back to back in the same alert window? (like "Write somethingWrite somethingWrite something..."):
If that is correct then your issue is your computation inside your for loop. You are simply add the two strings together, but doing nothing with the result. You need to save the result back to the someMsg variable on each loop iteration, like this:
var someMsg = promt("Write something");
var output = "";
for(var i=0; i<10; i++) {
output = output + someMsg;
}
alert(output);
You see how the result of output+someMsg is being saved back to the variable output with each iteration. You can also write that short hand like this:
output += someMsg;
Try this.
var someMsg=prompt("Write Something");
var i;
for(i=0;i<10;i++){
alert(someMsg);
}