Manipulating the DOM to get the maximum value among three numbers

I have a project that involves finding the largest value among 3 numbers. My goal is to input 3 numbers into the designated fields and then, upon clicking the Calculate button, display the biggest number after the main heading (h1). I am converting the inputs into numbers and creating an array out of them. Then, I loop through the array to compare each element with the first one in order to determine the maximum value. However, the code seems to be not working and I can't seem to identify the mistake. Would appreciate any help on this?

Here is the HTML structure:

 <!DOCTYPE html>
    <html>
    <head>
     <meta charset="UTF-8">
     <title>Max Value Of Three Numbers</title>

    </head>
    <body>
     <h1>The biggest number is: <span id="maxDisplay">0</span></h1>
     <input type="number" name="" id="num1">
     <input type="number" name="" id="num2">
     <input type="number" name="" id="num3">
     <button id="calculateMax">Calculate</button>

     <script type="text/javascript" src="maxValue.js"></script>
    </body>
    </html>

And here's the JavaScript part:

var maxDisplay = document.querySelector("#maxDisplay");

var number1 = document.getElementById("num1");
var num1 = Number(number1.value);
var number2 = document.getElementById("num2");
var num2 = Number(number2.value);
var number3 = document.getElementById("num3");
var num3 = Number(number3.value);
var arr = [num1, num2, num3];

var calculateMax = document.getElementById("calculateMax");

var maxNumber = 0;



calculateMax.addEventListener("click", function(){
    var maxNumber = arr[0];
    for (var i = 1; i < arr.length; i++) 
    {
        if(arr[i] > maxNumber) 
            { 
                maxNumber = arr[i];
            }
    }
    maxDisplay.textContent = maxNumber;

});

Answer №1

One reason for this issue is that the script tag in your HTML file fetches the values of input fields immediately (when loaded), resulting in them being empty at that point in time. To resolve this, simply rearrange your code as shown below.

var maxDisplay = document.querySelector("#maxDisplay");
var calculateMax = document.getElementById("calculateMax");
var maxNumber = 0;
var number1 = document.getElementById("num1");
var number2 = document.getElementById("num2");
var number3 = document.getElementById("num3");

calculateMax.addEventListener("click", function(){
    var num1 = Number(number1.value);
    var num2 = Number(number2.value);
    var num3 = Number(number3.value);
    var arr = [num1, num2, num3];

    var maxNumber = arr[0];
    for (var i = 1; i < arr.length; i++) {
        if(arr[i] > maxNumber)
            maxNumber = arr[i];
    }
    maxDisplay.textContent = maxNumber;

});

This modification ensures that you retrieve the values upon clicking the button instead. Additionally, you can obtain the maximum value from the array using a more concise method like so.

maxDisplay.textContent = Math.max.apply(null, arr);

Answer №2

const findMaxValue = () => {
    const maxDisplay = document.getElementById('maxDisplay');
    const num1 = document.getElementById('num1');
    const num2 = document.getElementById('num2');
    const num3 = document.getElementById('num3');
    const calculateBtn = document.getElementById('calculateMax');

    calculateBtn.addEventListener('click', function() {
        const numbers = [num1.value, num2.value, num3.value];
        maxDisplay.innerHTML = Math.max(...numbers);
    })
}
findMaxValue();
<html>
    <head>
     <meta charset="UTF-8">
     <title>Finding the Maximum Value</title>

    </head>
    <body>
     <h1>The maximum value is: <span id="maxDisplay">0</span></h1>
     <input type="number" name="" id="num1">
     <input type="number" name="" id="num2">
     <input type="number" name="" id="num3">
     <button id="calculateMax">Calculate Max</button>
    </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

Guide to deploying a factory contract using solidity @0.5.0 with Node.js

Repository: https://github.com/aljmiller87/ethereum-dispute-resolution In my solidity file @0.5.0, I have a Factory Contract and a child contract. Although I am able to compile it with some trial and error noted in the commented-out lines in ethereum/comp ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

The journey of a JavaScript file within an iframe devoid of any src attribute

Consider this scenario: In a folder labeled /jscript, there are two files named my_js_file1.js and my_js_file2.js. I also have an /index.html page structured like this: <html> <head> <script type='text/javascript' sr ...

Rendering Hexagonal Map Coordinates in HTML

After realizing that my hexagonal map's coordinate system is not suitable for certain findpath algorithms, I have decided to reform it. I found a new system that meets all my requirements, and you can check it out here. However, the example provided i ...

Extracting data from a CSV file and saving the information into an array

Currently, my goal is to parse a *.csv file. This *.csv file contains two columns that are delimited by a semicolon (";"). Through the use of a StreamReader, I am successful in reading the *.csv file and have been able to split each line using the Split( ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

What is the best way to exchange a variable in JavaScript with the output of AngularJS?

I implemented the search suggestion feature using HTML and JavaScript. In the app.js (Angular), I used $http.get to retrieve JSON data from a URL and stored it in $scope.JSONresult. Now, I want to update the list in HTML: ['b0','b12' ...

Using ES6 classes in Express routes: It is not possible to create the property 'next' on the string '/'

I'm currently working on integrating routes using classes in my express js application controller class User { constructor (){ this.username = 'me'; } getUsername(req,res){ res.json({ 'name& ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

Challenges arising from a node.js server and socket.io connection on a recurring basis

For a school project, I am developing a web application to display a sports game dashboard where multiple users can add or subtract points. Using socket.io and node.js, the application works perfectly on localhost but fails when deployed via cyclic at . Th ...

Creating an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

Include additional content following the text enclosed by the span tag, but do not place it

Take a look at this screenshot: https://i.sstatic.net/zojKK.jpg This code snippet allows me to include emoji spans within a DIV. $('body').on('click', '.selectable-icons', function(e) { if (e.target.tagName.toLowerCase( ...

Utilize Excel to automatically fill multiple cells with a specific value or formula, triggered by the content of a single cell

After completing the necessary computations for our math project, I have successfully found the values of the unknowns in a system of linear equations using matrix operations. The next task requires automating the process of filling a range of cells based ...

Updating a URL in an HTML form with JavaScript

Currently, I am faced with the task of manipulating a variable's value in a JS file within a function that is responsible for dynamically updating values in an HTML table without necessitating a full website reload. The function code snippet appears b ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

Is there a missing X-AppEngine-Region in the headers of the AppEngine application?

I've been trying to access the Region and Country in my request, but it seems like the X-AppEngine-Region and X-AppEngine-Country headers are missing. Sometimes I see headers like alt-svc content-length content-type date etag server status via ...

Locate the unordered list if its immediate parent is a list item

Here is the HTML code snippet I am working with: <div class="nav-collapse collapse"> <ul class="nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret">< ...

Using the scrollIntoView() method in VUE.js to center an li element within a component

One of the components I'm working with has multiple list items, and I want to achieve a functionality where clicking on any item will center it inside the component, making it visible in the center of the view. <card-maintenance v-for="m ...

Is there a way to retrieve the automatically generated ID for a document that was created with batch().set in Firestore?

Is there a method to retrieve the automatically generated ID for a document that is created as part of a batch operation in Firestore? Typically, when using .add(), obtaining an ID is straightforward: db.collection('posts') .add({title: &apos ...