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

Add a new component in front of another component based on its attribute value

Creating a dynamic DIV and positioning it in between other Div's based on their attribute value is the goal. The desired outcome is to maintain sequence. <div data-door="1">1</div> <div data-door="3">3</div> <div data-door ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

The Kenburn zoom image effect fails to function

I want to implement a zoom effect on an image using the Ken Burns effect when it is clicked. However, the code I have written does not seem to be working as expected. Here is the code snippet: $(document).ready(function () { $('.kenburns').on( ...

Exploring the art of reading and writing to a file with JavaScript and NodeJS

I am currently working on creating a function that will scan a file and remove all content below a specific line before adding new lines to the file. So far, I have successfully read the file and identified the target line: function analyze() { lineRe ...

Implementing async and await after making a fetch request

I am in the process of updating my code from using callbacks to utilize async and await. However, I am a bit confused on how to properly implement it within my current setup. The current setup involves: Clicking a button that triggers the clicker functi ...

Invoke the session on a different page and incorporate it into your JavaScript code

My php files, ajax.php and index.php, contain a mix of php code, html, and javascript. I am developing a quiz website where questions are retrieved from a database using sql in ajax.php and displayed on index.php through an ajax method. The user's sco ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

Having trouble getting the jQuery autocomplete feature to function properly?

On my page, there is a button labeled "Add a Skill." Clicking on this button should trigger the display of an input box where you can enter your skill, another input box for your skill level, and a horizontal slider to select the skill level. In my databa ...

What steps can I take to set a strict boundary for displaying the address closer to the current location?

While the autocomplete feature works perfectly for me, I encountered an issue where it suggests directions away from my current location when I start typing. I came across another code snippet that uses plain JavaScript to solve this problem by setting bou ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

Every time I attempt to insert a background image into a div using jQuery, I am consistently faced with a 404 error message

When I hit enter in my search bar, a new div is created each time. However, I am struggling to assign a background image to the created div as I keep receiving a 404 error in the console. Below is the code snippet I'm working with: function appendToD ...

How to resolve the error of "Cannot GET /api/courses/1"

const express = require('express'); const app = express(); app.get('/',(req,res) =>{ // viewable at localhost:3000 res.send('hello world'); }); app.get('/api/courses',(req,res) =>{ // shown on ...

React JS makes it simple to create user-friendly cards that are optimized

I have a collection of objects that include a name and description. The name is short and consists of only a few characters, while the description can vary in length. I am looking to showcase this data within Cards in my React project, and have tried using ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

Selecting JavaScript file on change as default option

Currently, I have an HTML file that prompts the user to select an XML file when the file selection is changed. Is there a way to make it so that by default, only one file is chosen? <form id='fileSelection' action=""> <center> <in ...

Duplicate key error occurred in the collection resulting in Error Handling: E11000

Encountering an issue with the user model I'm utilizing alongside Mongoose and MongoDB to create profiles in my database. The process works smoothly when posting a single user, but throws an error upon logging out and attempting to add another: { ...

Checking for the accuracy of the provided full name

There is a specific task at hand: The field labeled “First Name Last Name” must only contain 2 words, with each word being between 3 and 30 characters in length. Additionally, there should be only one space between the first and last name. The issue t ...