Adjusting form elements with Javascript

I'm looking to refresh my knowledge of JS by allowing users to input their first and last names along with two numbers. Upon clicking the button, I want the text to display as, "Hello Name! Your sum is number!"

I've encountered an issue in my code. Could someone please help me identify the problem?

<html>
<head>
<meta charset="UTF-8">
<title>JS Review</title>

<style>
    body{background: #8ADFB6; font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";}
    #container{background: white; padding: 30px; width: 760px; margin: 0 auto;}
    #output{
        padding: 10px; margin: 10px;
    }
</style>
</head>

<body>

<div id="container">

    <h1>Using Form Elements with Javascript</h1>


    <p>We can utilize user input to create feedback</p>
    First Name: <input id="first">
    Last Name: <input id="last">
    <p></p>
    Number 1: <input id="num1">
    Number 2: <input id="num2">
    <p></p>
    <button onClick="Respond()">Respond</button>

    <div id="output"></div>
</div>;

<script>
    function myFunction(){

        var a = document.getElementById("first").value;
        var b = document.getElementById("last").value;
        var c = document.getElementById("num1").value;
        var d = document.getElementById("num2").value;
        var n= document.getElementById("sum").value;

        var n= c + d;

        document.getElementById("Respond").innerHTML="Respond";

    }

    document.getElementById("Respond").innerHTML = "Hello! Your sum is !";


</script>
</body>
</html>

Answer №1

You seem to have encountered a few challenges.

First and foremost, it appears that you are attempting mathematical operations using string values. This can lead to concatenation instead of addition if not handled properly. To address this issue, consider validating the input to ensure they are actual numbers before proceeding with parsing them as floats.

if(isNaN(c) || isNaN(d) {
     alert('Invalid Input');
}else{
    var n= parseFloat(c) + parseFloat(d);
    document.getElementById("Respond").innerHTML = "Hello! Your sum is " + n;
}



Furthermore, there seems to be confusion regarding function names. It appears that you are calling a nonexistent function 'respond' instead of 'myFunction'. You may either update the function name in your JS code or adjust the HTML button accordingly.

This line:

function myFunction(){

should be:

function Respond(){

Or update this line in your HTML button:

<button onClick="myFunction()">Respond</button>



In addition, the element ID being referenced in your script does not match any existing elements. Make sure to use the correct ID ('output') for updating content.

This line:

document.getElementById("Respond").innerHTML = "Hello! Your sum is !";

Should be:

document.getElementById("output").innerHTML = "Hello! Your sum is " + n + "!";



Moreover, you are attempting to retrieve a value from an element with ID 'sum', which does not exist. Remove this line to avoid errors.

Simply delete this line:

var n= document.getElementById("sum").value;



Lastly, ensure that the value updater is inside the function scope where values are actually retrieved. Placing it outside will prevent proper updating of the displayed output.

It's important to thoroughly review your code to identify and rectify these issues. Taking the time to read through your code carefully can help prevent such problems in the future.

Answer №2

  1. You mistakenly referred to a function called Respond() in your button click handler instead of the correct function name myFunction() (or vice-versa).

  2. The values retrieved for Number 1 and Number 2 are in string format. You need to convert these values to integers by parsing them to perform mathematical calculations.

  3. Ensure you set the result to the innerHTML of #output, not

    #Respond</code. Use either Template Literals with String Interpolation or concatenation to combine the result, first name, last name, and the string <code>"Hello! Your sum is !"
    .

--

To concatenate, do this:

"a " + someVariableName + " is a fruit that has vitamin " + someOtherVariable

To use template literals and string interpolation:

`a ${someVariableName} is a fruit that has vitamin ${someOtherVariable}`

--

  1. Avoid using inline event handlers like onclick or oninput; instead, utilize event listeners in your JavaScript code.

Review and execute the following Code Snippet where I converted values and applied string interpolation to display the result when the button is clicked:

/* JavaScript */

function myFunction(){

  var a = document.getElementById("first").value;
  var b = document.getElementById("last").value;
  var c = document.getElementById("num1").value;
  var d = document.getElementById("num2").value;

  var n = parseInt(c) + parseInt(d);

  document.getElementById("output").innerHTML = `Hello ${a} ${b}! Your sum is ${n}!`;

}

document.querySelector("button").addEventListener("click", myFunction);       
<!-- HTML -->

First Name: <input id="first">
Last Name: <input id="last">
<p></p>
Number 1: <input id="num1">
Number 2: <input id="num2">
<p></p>
<button>Respond</button>

<div id="output"></div>

Answer №3

document.getElementById("num1").value;
retrieves a string value.

If you intend to perform mathematical operations, you must convert it into a numerical data type.

parseFloat(document.getElementById("num1").value);

Remember to incorporate input validation in your process to handle non-numeric entries effectively.

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

Learn how to retrieve the TextBox value from a button click within a Nested Gridview

I am trying to extract the value of a textbox inside a Nested Gridview using jQuery in ASP.NET. When a Button within the Nested Gridview is clicked, I want to display the textbox value in an alert box. Here is an example setup: <asp:GridView ID="Grid ...

Generate a series of buttons with generic identifiers that can be easily targeted using getElementById. The IDs will be dynamically assigned

I am looking to dynamically generate unique IDs for a list of buttons, allowing me to easily target specific buttons using getElementById. Here is an example code snippet where each button has the same ID: @foreach (var cat in Model) { <div clas ...

Switching between different CSS files based on the URL using jQuery or another method

Is it feasible to apply specific styles based on the ID or load various CSS files depending on the URL you are visiting? For example: <script> if(location.href == 'http://jpftest2.tumblr.com/about'){ document.write('<style type= ...

Using Angular to share JSON data efficiently between controllers

Greetings everyone, I am a beginner in Angular and not very skilled with JavaScript. The issue I'm facing is that although this setup successfully fetches the JSON data, whenever I modify certain object properties, they revert back to their original s ...

Angular Fire: The $on method is missing and causing an error stating that undefined is not a function

I am currently attempting to log my Firebase data to the console, but I keep encountering an error stating undefined is not a function. Below is the full error message: TypeError: undefined is not a function at Object.childAdded (http://localhost:9000/scr ...

Implementing a Push System without using node.JS

I am looking to develop a notification system similar to Facebook's, where notifications appear on the bottom-left side of the screen when someone interacts with your posts, for example. However, my challenge is that I need the server to send real-ti ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...

When I try to run "npm start" with node-webkit, it seems like the script specified in my package.json manifest file is not being

After running npm start in the terminal, I encountered the following error message: PS C:\Users\finsa\OneDrive\Documents\UNI\Web Development\NS_Music_App> npm start > <a href="/cdn-cgi/l/email-protection" class= ...

Maintain the tab order for elements even when they are hidden

Check out this demonstration: http://jsfiddle.net/gLq2b/ <input value="0" /> <input id="test" value="1" /> <input value="2" /> By pressing the TAB key, it will cycle through the inputs in order. If an input is hidden when focused, press ...

Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causi ...

In HTML5, a full-width video exceeds the size of the screen

When I have a video set to full width in a header with the width at 100%, the issue arises with the height. The video is too large, causing the controls to be out of view unless I scroll. Is there a solution to remedy this problem? <video width="100%" ...

An effective way to pass a value using a variable in res.setHeader within express.js

Attempting to transmit a file on the frontend while including its name and extension. var fileReadStream = fs.createReadStream(filePath); res.setHeader("Content-disposition", `attachment; filename=${fileName}`); fileReadStream.pipe(res); Encount ...

Tips for effectively transmitting and managing a JSON object within an ASP.NET MVC controller

I am currently working on a project using ASP.NET MVC 4 and I'm facing an issue with sending a JSON object to a controller that is supposed to accept it. Here is the snippet of javascript and jQuery code I am using: var jsonObject = { "PlantShip ...

Multiple executions of Ajax callback detected

I am trying to utilize an ajax-call to a script that searches for numbers. The response is expected to be a json array containing names and surnames as strings. However, I am facing an issue where the script seems to be looping and sending multiple respons ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

Modifying the status of a link using jQuery

My ajax function handles two different outcomes based on the class of the link that is clicked. To avoid reloading the entire page when the link is clicked, I have utilized the following code: Everything seems to be working fine, however jQuery still rec ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

Displaying the getJSON output only once, then having it automatically update at regular intervals without any repetitive results

I previously had an issue resolved on stackoverflow, but the requirements of my project have changed. Therefore, I am in need of a new solution. In summary, I have a getJSON function that runs every 5 seconds to check for changes in a JSON file. The proble ...