Can someone advise me on how to ensure my function effectively delivers a desired outcome?

My goal is to learn Javascript on my own, but I'm struggling to make progress. I've created a function called fixedSpending() that takes two inputs, num1 and num2, and adds them together. However, when the user hits the "=" button, I expect the function to return the total. Unfortunately, this isn't happening as I keep encountering an uncaught reference error in the console stating that fixedSpending() is not defined. I'm confused as to why this error is occurring.

I would greatly appreciate any assistance or resources for learning more about this topic.

 <html>
    
    <head>
      <title>
        Budget Form
        <script type="text/javascript">
        function fixedSpending(){
          var num1=parseFloat(document.getElementById("num1").value)
          var num2=parseFloat(document.getElementById("num2").value)
    
          return document.getElementById('result').value= num1 + num2;
        } 
        </script>
      </title>
    
    </head>
    <body>
      <h2></h2>
      <br>
      num1:&nbsp;<input type="text" id="num1" maxlength="10"><br>
      num2:&nbsp;<input type="text" id="num2" maxlength="10"><br>
      <input type="Button" value= "=" onclick="fixedSpending();"><br>
      Result: <input type="text" id="result">
    </body>
</html>

The error message reads: Uncaught ReferenceError: fixedSpending is not defined

Answer №1

It appears that there is an issue with your HTML code. The <script> tag should not be placed inside the <title> tag. To resolve this, you just need to move the <script> tag outside of the <title> tag. Here is the corrected code:

<html>
    <head>
        <title>Budget Form</title>
        <script type="text/javascript">
            function fixedSpending(){
                var num1 = parseFloat(document.getElementById("num1").value);
                var num2 = parseFloat(document.getElementById("num2").value);

                return document.getElementById('result').value = num1 + num2;
            }
        </script>
    </head>
    <body>
        <h2></h2>
        <br>
        num1: &nbsp;<input type="text" id="num1" maxlength="10"><br>
        num2: &nbsp;<input type="text" id="num2" maxlength="10"><br>
        <input type="Button" value="=" onclick="fixedSpending();"><br>
        Result: <input type="text" id="result">
    </body>
</html>

Answer №2

To start, take the script out of the title tag as it is currently nested inside.

Next, relocate the script to right above the closing body tag. This ensures that the form fields are fully rendered before any manipulation or data usage takes place, following common practice.

Lastly, eliminate the term "return" from your function. The function does not require a specific return value since it only needs to set the result field's value. Simply remove "return" from the final line of your function.

Answer №3

According to @Bjarke's observation, it seems that your script is not properly embedded within the HTML document. To rectify this issue, make sure to place the script just above the closing </body> tag. Additionally, there is no need to use the return statement as you are simply assigning a value to an input field. You can try the following corrected code:

<html>
  <head>
    <title>
      Budget Form
    </title>
  </head>
  <body>
    <h2></h2>
    <br>
    num1:&nbsp;<input type="text" id="num1" maxlength="10"><br>
    num2:&nbsp;<input type="text" id="num2" maxlength="10"><br>
    <input type="button" value= "=" onclick="fixedSpending();"><br>
    Result: <input type="text" id="result">
    <script>
        function fixedSpending() {
            var num1 = parseFloat(document.getElementById("num1").value)
            var num2 = parseFloat(document.getElementById("num2").value)
            document.getElementById('result').value = num1 + num2;
        };
    </script>
  </body>
</html>

Feel free to test this adjusted code on jsfiddle: https://jsfiddle.net/mzvnfow2/2/

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

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

Having difficulty choosing an element with protractor's virtual repeat functionality

Initially, I successfully used ng-repeat to select an element. However, the developers have since implemented virtual repeat which has caused the following code to stop working: expect(stores.listStores(0).getText()).toContain('Prahran'); expect ...

Keep the multiselect dropdown list of the select component open

I am currently utilizing the Select component from material-ui-next. Overall, it functions quite smoothly. One scenario where I implement it is within a cell element of an Ag-Grid. Specifically, in this use case, I am making use of the multiselect feature ...

The V-model is failing to bind properly as anticipated

One feature of my application involves a table that displays a list of products. Each product row in the table has an input field where users can enter the quantity they want to purchase. The total cost for each product is dynamically calculated by multipl ...

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

Transforming a form submission into an AJAX post while already in an AJAX post

I am looking to convert a form submission to an ajax post request while working within the codeigniter framework. The current JavaScript code is: $('#book-appointment-submit').click(function(event) { event.preventDefault(); var formData ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Honing in on JavaScript Media Queries within React

I have been attempting to incorporate the media query concept from a resource I found here in my React project. However, when testing the code snippet below, I encountered the following error: TypeError: isMobile.addListener is not a function function App ...

Leaflet.js obscuring visibility of SVG control

I am currently working with Leaflet 0.7.1 and I am looking to create a radial menu (similar to openstreetmap's iD editor) using d3 and display it on top of the map. I have come across some examples that use Leaflet's overlayPane to append the svg ...

Using Angular JS, send out a notification and pause execution until it is finished

I recently encountered an interesting situation involving an Angular event: $rootScope.$broadcast("postData"); doSomething(); However, I realized that doSomething() needs to wait for the completion of postData before executing. This led me to contemplate ...

JavaScript: Closing a Tab

Using AngularJS for my project and I have a link that opens a tab. If the user right clicks on the link and selects open link in new tab, then on the page abc.html I have code like $window.close(); which is not working as expected. I am receiving the error ...

Determine the dropdown list value by analyzing the final two variables in a textfield

In my textfield, car registration numbers are meant to be entered. These registrations are based on years in the format GT 74454 12, with the last two digits "12" representing the year 2012. I am looking for a script that can automatically detect the last ...

When working with Node.js and Express, I encountered an issue where the req.session object was not defined within

It's peculiar to me that req.session.username is undefined in the tag >>>DOESNT WORK<<< while it works in the tag >>>THIS DOES WORK<<<. I passed req as an argument to my module, but it seems like there might be something else at play here? The /ajax r ...

Steps for regularly executing 'npm run build' on the server

My website doesn't require frequent content updates, as users don't always need the latest information. As a result, most pages are generated server-side and served as static pages. There will be occasional database updates that need to be visib ...

How can I retrieve data during a double-click event in Kendo Grid using Angular?

How can I retrieve data on the doubleClick event in a Kendo Grid? I want to access the same object that is fetched during the selected event, which would be the dataitem at the selected index row. HTML: <kendo-grid #myGrid [data]="gridDat ...

Tips on creating a button that, upon clicking, triggers the download of an Excel file using PHPSpreadsheet

I am trying to figure out how to create a button that, when clicked, will download an Excel file named b1b5.xls with some specified values added. Here is the code I have so far: <html> <head> </head> <body> <center> < ...