What could be causing this code to keep looping?

This is my submission for a class project. The task given was:

"Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a number to be used later. Also from the main() function, call a function called getSquareRoot(). The getSquareRoot() function will calculate the square root of the number obtained from the user in the getValue() function. Ensure that you present the results, including the original number and its square root, in a format that is easy to comprehend.

The bolding is part of the original text.

I have written the code below, and it functions properly, except for the fact that some functions are triggered twice, leading to double output display during the second run where userInput receives a value of 0. I am struggling to identify where this 'loop' is being initiated (I am a beginner). Any assistance would be greatly appreciated; I've been staring at it but unable to pinpoint the issue.

<html lang="en">

<head>
<title>Project 3 Part A</title>

    <meta charset="utf-8">      

    <script>

        function main()
        {

            var msg1="";
            var msg2="";                
            var userInput = "";

            getValue(userInput);
            getSquareRoot(userInput);

        }

        function getValue(userInput)
        {

            var userInput = document.getElementById("userNumber").value;
            return getSquareRoot(userInput);

        }

        function getSquareRoot(userInput)           
        {           

            squareRoot = Math.sqrt(userInput);  
            var msg1 = "Your original number was " + userInput + ".";   
            var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";   
            document.getElementById("original").innerHTML += msg1;
            document.getElementById("results").innerHTML += msg2;

        }




    </script>

</head>

<body>

        <br>

    <input type="button" id="userInputButton" onclick="javascript:main();" value="Square root input value: "/>          

    <input type="text" id="userNumber"> 

    </div>

    <div id="original">

    </div>

    <div id="results">

    </div>                      

</body>

Please feel free to provide your insights on how to resolve the duplication issue.

Answer №1

It is important to ensure that each function has a single purpose for optimal efficiency. In this case, the function 'getSquaredRoot' handles both calculating the square root and displaying the result to the user.

Additionally, as mentioned by Lucky Chingi, the getSquaredRoot function is being called twice.


function main() {
    var userInput = getUserInput();        
    var squareRoot = calculateSquareRoot(userInput);

    var message1 = "Your original number was " + userInput + ".";   
    var message2 = "The square root of " + userInput + " is " + squareRoot + ".";   
    document.getElementById("original").innerHTML += message1;
    document.getElementById("results").innerHTML += message2;

}

function getUserInput() {
    return document.getElementById("userNumber").value;
}

function calculateSquareRoot(userInput) {           
    return Math.sqrt(userInput);  
}

This structure provides clear logical separation of functions.

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

JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

What is the method for obtaining the most up-to-date JSON GET request URL?

Using JQGrid with search filters and setting loadOnce=false. I perform a search in the grid and observe the JSON request URL in firebug: http://localhost:8080/myapp/items/listGrid?ticketId=&_search=true&nd=1393573713370&rows=20&page=1& ...

Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller. Service: class userService { constructor ($http, ConfigService, authService) { th ...

Display a particular div upon clicking a specific link, while concealing the other divs

As a beginner in the world of jQuery and coding, I'm encountering some difficulties that I need help with. My goal is to have the 'Vlogging' link activated and show 'Details 1' when the page loads. Then, upon clicking on either &a ...

Check to see if the ContentEditable div is currently focused

I'm struggling to determine if a contenteditable div has focus with my current code. Here is what I have so far: if ($("#journal-content:focus")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } The issue I'm encounter ...

Creating a responsive Google map within a div element: A step-by-step guide

I am experiencing difficulties with implementing a responsive Google map on my webpage. To achieve a mobile-first and responsive design, I am utilizing Google Map API v3 along with Bootstrap 3 CSS. My objective is to obtain user addresses either through th ...

Oops! Looks like there's a problem with the helper called "if_equal" in Handlebars

I attempted to incorporate handlebars into my express node application, but it appears to be malfunctioning. const express = require('express'); const hbs = require('hbs'); const expressHbs = require('express-handlebars'); c ...

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& ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Incorporating AJAX functionality into an existing PHP form

I am currently working on a PHP registration form that validates user inputs using $_POST[] requests. Validating username length (3-20 characters) Checking username availability Ensuring the username matches /^[A-Za-z0-9_]+$/ pattern and more... Instead ...

What is the best way to retrieve the current font size of a link element?

Is there a way to determine the font size of an element in pixels or points? Are there alternative methods available to achieve this? I am looking to increase the size of <a href="...">MAKE ME BIGGER</a> by 130%, 140%, N% based on its current ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

Problem encountered with JQuery Sparkline in Internet Explorer

I recently implemented jQuery sparkline on a webpage, sourced from . However, I encountered an issue with Internet Explorer when the container DIV is not large enough to display it properly. Surprisingly, the code worked perfectly fine in Firefox and Chrom ...

Is it advisable to incorporate vue-resource in Vuex actions?

I am currently working on a web application that retrieves airport data from the backend. To manage states and data sharing, I am utilizing Vuex. My dilemma is whether to load the airports in my Vuex actions or within a method of my Vue instance which will ...

Could you walk me through the details of this React function?

Currently, I have a function in place that retrieves products from the database to display on the eCommerce website's product page. Now, I am working on creating a similar function for user sign-in. Could you lend me a hand with this? I'm still ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...