.innerHTML not updating with new score in arithmetic assessment

For a school project, I am working on creating a completely randomized math quiz utilizing HTML, CSS, Javascript, and possibly JQuery. The quiz should involve three different operators and must also be visually appealing with CSS styling.

I've encountered an issue where the question doesn't display within the designated 'questions' div. Since this is my first time using JavaScript, I realize that there may be several errors in my code. Any assistance or guidance would be greatly appreciated. If you require the full code, please let me know. Thank you.

function getNumber(){
    var oplist = ["=", "-", "*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist[Math.floor(Math.random() * oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;

Answer №1

Utilize the following code snippet within the function:

return  num1 + op + num2+'='+ans;

var num1,num2,op
var ans =0;
function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
    return  num1 + op + num2+'='+ans;
}

document.getElementById("questions").innerHTML = getNumber();
<p id="questions"></p>

Answer №2

<!DOCTYPE html>
<html>
<head>
    <title></title>
        <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-3.2.1.js"
            integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
            crossorigin="anonymous"></script>
</head>
<body>
<div id="queries"></div>
    <div>
        <input type="button" onclick="generateNumber()" />
    </div>
</body>
</html>

<script>

        function generateNumber() {
            var operators = ["=", "-", "*"];
            num1 = Math.floor((Math.random() * 10) + 1);
            num2 = Math.floor((Math.random() * 10) + 1);
            operation = operators[Math.floor(Math.random() * operators.length)];
            if (operation == "+") {
                answer = (num1 + num2)
            }
            else if (operation == "-") {
                answer = (num1 - num2)
            }
            else if (operation == "*") {
                answer = (num1 * num2)
            }

            document.getElementById("queries").innerHTML = num1 + operation + num2;
        }
</script>

Answer №3

You haven't invoked your function yet

document.getElementById("questions").innerHTML = getNumber();

function getNumber(){
    var oplist = ["=","-","*"],
    num1 = Math.floor((Math.random() * 10) + 1),
    num2 = Math.floor((Math.random() * 10) + 1),
    op = oplist [Math.floor(Math.random()* oplist.length)],
ans = 0;
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
return ans;
}

document.getElementById("questions").innerHTML = getNumber();
<div id="questions"></div>

Answer №4

Here is an example of what your code could look like.

<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
<div id="questions"></div>
    <div>
        <input type="button" onclick="getNumber()" value="Get Answer"/>
    </div>
<script>

        function getNumber() {
            var operatorList = ["=", "-", "*"];
            num1 = Math.floor((Math.random() * 10) + 1);
            num2 = Math.floor((Math.random() * 10) + 1);
            op = operatorList[Math.floor(Math.random() * operatorList.length)];
            if (op == "+") {
                ans = (num1 + num2)
            }
            else if (op == "-") {
                ans = (num1 - num2)
            }
            else if (op == "*") {
                ans = (num1 * num2)
            }

            document.getElementById("questions").innerHTML = num1 + op + num2;
        }
</script>
</body>
</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

Can you please explain the function of this JavaScript code for the Isotope filter?

I am struggling to grasp the functionality of a section of vanilla JS code related to the Isotope filter. You can find the original code here. var buttonGroups = document.querySelectorAll('.button-group'); for (var i = 0; i < buttonGroups.le ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

Tips for utilizing the vuetify readonly prop while enabling the selection menu

In my project, I have a grid containing v-autocomplete components with the multiple attribute. To maintain clean formatting, I decided to show only a shortened version of the content using the selection slot feature provided below: <v-autocomp ...

The functionality does not seem to be functioning in Mozilla Firefox, however it is working correctly in Chrome when the following code is executed: `$('input[data-type="choise"

I am currently working on an online test portal and everything is functioning properly with Chrome. However, I am encountering an issue with Mozilla Firefox. My code works fine in Chrome but not in Mozilla Firefox. Please suggest an alternative solution to ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

Display JSON data in AngularJS and show the corresponding data on the right side when clicked

I'm brand new to using AngularJS and I've been struggling with this issue. Take a look at the code snippet below to see what I mean. The titles are shown on the left, and when you click on one, I want the corresponding body to display on the righ ...

Shrinking dropdown CSS navbar

Recently, I added a dropdown menu to my website which can be seen here: . However, I am experiencing an issue where the dropdowns are closing too soon. Sometimes it's challenging to keep the dropdown open when trying to select an option from within it ...

Receive a positive or negative data message through Ajax Response

Exploring Ajax for the first time, I am eager to incorporate database interaction using AJAX in JQUERY by connecting to a PHP script. $(function() { $.ajax({ type: "POST", url: "response.php", ...

Including file format extension in the absence of one

I have created a script that loops through every image source on the page, extracting the extension. If the extension is not recognized or does not exist, I automatically add .jpg to the end. Strangely, the if statement always evaluates to true no matter ...

The elements on the webpage are spilling over with content

I encountered an issue while creating a dashboard with a sidebar on the left side. When adding content to the page, some of it ended up hidden behind the sidebar. I tried using overflow-x:auto and this was the result: https://i.stack.imgur.com/5qHJY.jpg Be ...

CSS: Crafting a unique image layout with scissor-cut design

This design uses a PNG image created in Photoshop: When it comes to images: Notice how the shape resembles a trapezium with one perpendicular side and another tilted. How can we achieve this layout using HTML/CSS, so that any image placed inside this di ...

The <entry> rises above the backdrop of my introduction

Having trouble with my website development... I want to insert an <article> after the <header> with a full-screen background intro, but it seems to overlap with my <div> even though it's in the header and the article is in the body. ...

Is there a way to see the default reactions in a browser when keyboard events such as 'tab' keydown occur?

Whenever I press the 'tab' key, the browser switches focus to a different element. I would like to be able to customize the order of focused elements or skip over certain elements when tabbing through a page. While I am aware that I can use preve ...

creating an array of piecharts with varying sizes in raphaeljs

I have a task to visually represent the voting results stored in a MySQL database. Each question in the database has corresponding answers, with each answer containing 5 numerical values. The list below shows the questions and their respective answers: Q1 ...

Achieving a Collapsible Top Navigation with Additional Selection in Bootstrap 4

Adding a new section above the current <nav>. This is what I hope will occur. https://i.sstatic.net/HBaYN.png Below is my code: https://jsfiddle.net/rLc588mu/ Appreciate your assistance! ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

Is the JSON response in the AJAX request accurate, even though the content is not being refreshed?

I have a function that is triggered in the following manner: success: function(json) { if(json.valid == 1) { // Another show/hide operation that functions properly $("#div-response-" + id).html(json.message); } ...

Is it possible to extract the version_name using the version_code of an android package?

Is it possible to retrieve the version_name by using the version_code of an Android package? For instance: 'com.nianticlabs.pokemongo' version_code: 2017121800 => version_name: 0.87.5 I'm looking for a function that can accomplish th ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...