I seem to be having trouble with this JavaScript code. Could it be a syntax error, or is it possibly another issue causing it

I am encountering an issue with this code, as it is not functioning as intended. Although, I am unsure about the root of the problem.


Code:

<body>
  var randNumForQuote = Math.floor((Math.random() * 11));

  if (randNumForQuote == 0) {
    document.getElementById("quoteDiv").innerHTML = "Hello";
  } else if (randNumForQuote == 1) {
    document.getElementById("quoteDiv").innerHTML = "Hello1";
  } else if (randNumForQuote == 2) {
    document.getElementById("quoteDiv").innerHTML = "Hello2";
  } else if (randNumForQuote == 3) {
    document.getElementById("quoteDiv").innerHTML = "Hello3";
  } else if (randNumForQuote == 4) {
    document.getElementById("quoteDiv").innerHTML = "Hello4";
  } else if (randNumForQuote == 5) {
    document.getElementById("quoteDiv").innerHTML = "Hello5";
  } else if (randNumForQuote == 6) {
    document.getElementById("quoteDiv").innerHTML = "Hello6";
  } else if (randNumForQuote == 7) {
    document.getElementById("quoteDiv").innerHTML = "Hello7";
  } else if (randNumForQuote == 8) {
    document.getElementById("quoteDiv").innerHTML = "Hello8";
  } else if (randNumForQuote == 9) {
    document.getElementById("quoteDiv").innerHTML = "Hello9";
  } else if (randNumForQuote == 10) {
    document.getElementById("quoteDiv").innerHTML = "Hello10";
  }

  <div id="quoteDiv"></div>
</body>


My knowledge in JavaScript is limited, which makes it challenging for me to pinpoint the issue.

I anticipate the div to display one of the potential outputs (e.g., Hello, Hello1, Hello2, etc.)

Answer №1

To incorporate the JavaScript code, it is essential to enclose it within the script tag and execute it once the page has finished loading. This can be accomplished by placing it inside the window.onload callback, which triggers at the conclusion of the document loading sequence.

<body>
  <script>
    window.onload = function() {
      var randNumForQuote = Math.floor((Math.random() * 11));

      if (randNumForQuote == 0) {
        document.getElementById("quoteDiv").innerHTML = "Hello";
      } else if (randNumForQuote == 1) {
        document.getElementById("quoteDiv").innerHTML = "Hello1";
      } else if (randNumForQuote == 2) {
        document.getElementById("quoteDiv").innerHTML = "Hello2";
      } else if (randNumForQuote == 3) {
        document.getElementById("quoteDiv").innerHTML = "Hello3";
      } else if (randNumForQuote == 4) {
        document.getElementById("quoteDiv").innerHTML = "Hello4";
      } else if (randNumForQuote == 5) {
        document.getElementById("quoteDiv").innerHTML = "Hello5";
      } else if (randNumForQuote == 6) {
        document.getElementById("quoteDiv").innerHTML = "Hello6";
      } else if (randNumForQuote == 7) {
        document.getElementById("quoteDiv").innerHTML = "Hello7";
      } else if (randNumForQuote == 8) {
        document.getElementById("quoteDiv").innerHTML = "Hello8";
      } else if (randNumForQuote == 9) {
        document.getElementById("quoteDiv").innerHTML = "Hello9";
      } else if (randNumForQuote == 10) {
        document.getElementById("quoteDiv").innerHTML = "Hello10";
      }
    }
  </script>

  <div id="quoteDiv"></div>
</body>


There is a way to streamline the code

<body>
  <script>
    window.onload = function() {
      var randNumForQuote = Math.floor((Math.random() * 11));
      document.getElementById("quoteDiv").innerHTML = "Hello" + (randNumForQuote ? " " + randNumForQuote : '');
    }
  </script>

  <div id="quoteDiv"></div>
</body>

Answer №2

In order to include Javascript in an HTML document, it must be enclosed within a script tag. Additionally, the div element should be placed before the script tag.

<body>
  <div id="quoteDiv"></div>
<script>
  var randNumForQuote = Math.floor((Math.random() * 11));

  if (randNumForQuote == 0) {
    document.getElementById("quoteDiv").innerHTML = "Hello";
  } else if (randNumForQuote == 1) {
    document.getElementById("quoteDiv").innerHTML = "Hello1";
  } else if (randNumForQuote == 2) {
    document.getElementById("quoteDiv").innerHTML = "Hello2";
  } else if (randNumForQuote == 3) {
    document.getElementById("quoteDiv").innerHTML = "Hello3";
  } else if (randNumForQuote == 4) {
    document.getElementById("quoteDiv").innerHTML = "Hello4";
  } else if (randNumForQuote == 5) {
    document.getElementById("quoteDiv").innerHTML = "Hello5";
  } else if (randNumForQuote == 6) {
    document.getElementById("quoteDiv").innerHTML = "Hello6";
  } else if (randNumForQuote == 7) {
    document.getElementById("quoteDiv").innerHTML = "Hello7";
  } else if (randNumForQuote == 8) {
    document.getElementById("quoteDiv").innerHTML = "Hello8";
  } else if (randNumForQuote == 9) {
    document.getElementById("quoteDiv").innerHTML = "Hello9";
  } else if (randNumForQuote == 10) {
    document.getElementById("quoteDiv").innerHTML = "Hello10";
  }
</script>
</body>

Answer №3

<html>
<body> 
    <div id="quoteDiv"></div>



</body>
<script>
// function to display random quote

   var randNumForQuote = Math.floor((Math.random() * 11));

  switch (randNumForQuote) {
    case 0:
        document.getElementById("quoteDiv").innerHTML = "Hello";
        break;
    case 1:
        document.getElementById("quoteDiv").innerHTML = "Hello1";
        break;
    case 2:
        document.getElementById("quoteDiv").innerHTML = "Hello2";
        break;
    case 3:
        document.getElementById("quoteDiv").innerHTML = "Hello3";
        break;
    case 4:
        document.getElementById("quoteDiv").innerHTML = "Hello4";
        break;
    case 5:
        document.getElementById("quoteDiv").innerHTML = "Hello5";
        break;
    case 6:
        document.getElementById("quoteDiv").innerHTML = "Hello6";
        break;
    case 7:
        document.getElementById("quoteDiv").innerHTML = "Hello7";
        break;
    case 8:
        document.getElementById("quoteDiv").innerHTML = "Hello8";
        break;
    case 9:
        document.getElementById("quoteDiv").innerHTML = "Hello9";
        break;
    case 10:
        document.getElementById("quoteDiv").innerHTML = "Hello10";
        break;
  }
</script>

</html>

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

Is there a potential race condition in React when switching between lists?

I'm currently working on setting up a queue system where users can move items between different lists, such as from "available" to "with client". The queue's state is managed in the root React component like this: this.state = { queue: { a ...

with every instance of an ajax request sent to a separate file

Currently, I have a forEach function that is printing the "local" column from a specific database: View image here Everything is working well up to this point, and this is the output I am getting: See result here Now, my goal is to send variables via P ...

Tips for achieving a Google Map that smoothly slides behind a sticky header as you scroll

I recently added a sticky header using CSS to my long HTML page. At the bottom of the page, there is a <div> element with a Google Map embedded in it. As I scroll down the page, the content scrolls behind the sticky header as expected, but the Googl ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

Utilizing Vuejs and ElementUi to enhance slot filtering capabilities

I am facing an issue with a table where one of the columns is using slot-scope, and I am struggling to include that column data into the filters option. Code Component filter input <el-input v-model="filters[0].value" placeholder="Type t ...

How come my data is not appearing on the screen despite receiving a result in the console log?

I am facing an issue with displaying data obtained from Supabase. I am passing the data as a prop and using map to iterate over it in order to show the required values. However, despite logging the correct results for `programme.title`, nothing is being re ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

angularjs ng-repeat utilizing the index instead of names

Using ng-repat to populate an HTML table with an array has been causing some naming normalization issues for me. Dealing with stubborn users, I am now in search of a quick workaround. Sometimes my array AgendaItems appears as: {"Agenda Item":&q ...

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

Using Background Images in Emails with HTML

Struggling to add a background image with overlaid text? I've attempted multiple methods without success. Can someone provide a foolproof solution for achieving this? Thank you. ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Database function call is not producing any results

Initially, the code below was intended to create a new user when starting the quiz, but now it is meant to update an existing user's details. However, I am facing an issue where the addUser() function is not completing as expected even though all inpu ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

I'm working on creating a login page with Bootstrap. Does anyone know the best way to center it on the screen

For a school project, I am working on creating a sign-in page. Although I have come across this code, it does not appear at the center of the page as intended. Instead, the left side displays to the left while the right side shows up to the right. My goal ...

Are the charts missing from the Django admin interface?

I am working on incorporating charts into my admin view by extending the admin/base.html file. Instead of using libraries like charts.js, I prefer to use a template for displaying the charts. Ideally, I want my view to resemble this example (). You can fin ...

Is it possible to build an AngularJS application without utilizing HTML5?

Having created an AngularJS application, I have noticed that it functions smoothly on modern browsers. However, some of my devices run on old browsers that do not support html5. Unfortunately, I am unable to upgrade these browsers. Is there a method to ope ...

Is there a way to use JavaScript to choose options within a <select> element without deselecting options that are disabled?

Here's the code snippet I am working with at the moment: <select id="idsite" name="sites-list" size="10" multiple style="width:100px;"> <option value="1" disabled>SITE</option> ...

What are the different scenarios in AngularJS where $scope is utilized versus when var is utilized?

Which is more efficient in AngularJS: using var or $scope. for variables inside functions? I am asking this question because I recently came across information about $watch, $digest, and $apply in AngularJS. While I may not have fully grasped the concept ...

A method to apply a class to the third <li> element using javascript

Can someone help me figure out how to add a class to the third element using Javascript? Here is the structure I am working with: <ul class="products-grid row four-columns first"> <li class="item"></li> <li class="item"></li&g ...

Integrating a neighborhood library with an Angular 5 Project

I want to have a local library that can reflect changes in the project using it. I have cloned the library from this link on my local machine: https://github.com/manfredsteyer/angular-oauth2-oidc Currently, I am navigating to the library directory and run ...