Is it possible that only one number is printed when document.getElementById("demo").innerHTML = Math.ceil((Math.random()*10)-1); is executed?

How come the code

document.getElementById(“demo”).innerHTML = Math.ceil((Math.random()*10)-1);
is only displaying one number?

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    document.getElementById("demo").innerHTML = Math.ceil((Math.random() * 10) - 1);

  }
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

Answer №1

When updating the content using innerHTML, it's important to add to the existing content rather than replacing it entirely.

To append new content, use += instead of just =:

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    document.getElementById("demo").innerHTML += Math.ceil((Math.random() * 10) - 1);

  }
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>


EDIT:

Following @Robin Zigmond's suggestion, it is actually more efficient to build a string and then append that string to innerHTML once after the loop has completed:

function myFunction() {
  var bbb = document.getElementById("ilgis").value;

  var numbers = "";
  for (i = 0; i <= bbb; i++) {

    //document.writeln(aaa);
    numbers += Math.ceil((Math.random() * 10) - 1);

  }
  document.getElementById("demo").innerHTML = numbers;
}
<input type="number" id="ilgis" value="123">

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Calculate the sum of hours worked in a day using pure JavaScript, no external libraries required

Hello, I'm new to this website and please excuse me if my English is not perfect, I am trying my best to communicate :) I have been working on a page that calculates the total hours worked in a day and this is what I have achieved so far until 15/06 ...

Encountering a 404 error when translating URLs in Next.js i18n?

I am developing a multilingual service utilizing next-i18next. I wanted to have some of my routes translated as well, for example: EN: /contact => default language IT: /fa/ارتباط-با-ما => second language To achieve this, I utilized tran ...

Transform SVG with a Click

Can someone assist me with rotating the pink area on click and moving it to a new angle from its current position? I am looking for a way to save the current position of the pink area and then, when clicked, move it smoothly to a new position. Your help ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

How to access a $scope variable in the same Angular controller function from outside the function

As a newcomer to AngularJS, I have a question about accessing my $scope variable from an outside function within the same controller. How can I achieve this? Below is the code snippet: .controller('RekapCtrl', ['$scope', '$timeout ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

How do I use Puppeteer to save the current page as a PDF?

Is it possible to convert a web page in a React project to PDF and download it upon clicking a button? ...

AgGrid Encounters Difficulty in Recovering Original Grid Information

After making an initial API call, I populate the grid with data. One of the fields that is editable is the Price cell. If I edit a Price cell and then click the Restore button, the original dataset is restored. However, if I edit a Price cell again, the ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

Updating the columns in a row by clicking the refresh button with ajax in a JSP file

Hey there! I have a table on my JSP page with refresh buttons at the row level. When I click the refresh button, it should check the database and update those two columns with new values. Below is the code snippet for my JSP page: <script src="js/jque ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

The functionality of Vue JS v-attr="expression1 && exp2 && exp3" seems to be malfunctioning

Why aren't Vue JS v-attr=“expression1 && exp2 && exp3” working? I've attempted using ${&}${&}, #{&}#{&}, &amp;&amp;, and even #{&amp;}#{&amp;} The code can be found on JSFiddle <div id="dem ...

Looking to clean up unnecessary <b></b> tags from my Wordpress website - how can I do this?

One of my sites is located at . When inspecting the source code through the browser, I noticed the presence of empty tags. Does anyone know why these empty tags are being generated and how they can be removed? I have thoroughly searched through all files ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...

Issue with JSONP request in jQuery/AJAX

I am currently attempting to make a request to a different site, which requires authentication through a cookie. Oddly enough, when I try making the call like this : $.getJSON(url + '?', function(data){ alert(data); }); The HTTP headers do ...