How can JavaScript be used to dynamically display submitted HTML form values on the same page, as well as how to perform calculations on the form data?

Currently, I am working on creating a form for collecting passenger information at an airport. The form includes fields for first name, last name, passenger weight, and cargo weight. Upon submitting the form, I aim to display the entered information along with the total weights of passengers and cargo. The process is meant to continue until all passenger details are collected. Ultimately, I want to keep track of the total weight that the plane will be carrying.

I have already set up the form, but I am struggling to implement the functionality using my basic knowledge of JavaScript. I have assigned an onclick function to the submit button and defined it as follows:

<form  id="Passenger-form" onsubmit="return false">
         <label for="First-name">First name: </label>
         <input type="text" name="First-name" placeholder="Please insert first name."><br>
        <label for="Second-name">Second name:   </label>
        <input type="text"  name="Second-name"   placeholder="Please insert second name"> <br>
        <label for="Passenger-weight">Passengers weight:   </label>
        <input type="number" name ="Passenger-weight"  placeholder="Please enter passengers weight"><br>
        <label for="cargo-weight">Cargo weight:   </label>
        <input type="number"  name ="cargo-weight" placeholder="Please enter cargo weight"><br>
       <input type="submit" name ="submit" onclick="showInput(); multiply(); ">
      </form>
      <p > <span id="display"></span></p>
      
      
<body>
 <script language="JavaScript">
   
   function showInput() {
   document.getElementById('display').innerHTML = 
   document.getElementById("First-name").value +" "+ document.getElementById("Second-name").value;
    }

    function multiply(){
    num1 = document.getElementById("Passenger-weight").value;
     num2 = document.getElementById("cargo-weight").value;
     document.getElementById("display").innerHTML = num1 + num2;
    }
  </script>

I know I still have a long way to go in resolving this issue, so any help would be greatly appreciated. Additionally, dealing with the JavaScript "+" sign has been particularly challenging for me as I struggle to use it as an operator.

Answer №1

There are a variety of methods to accomplish this task. One option is to specify the onClick directly within the HTML:

<script>
  function x() { return y; }
</script>
<body>
     <button onClick="x()">Click Here</button>
</body>

Another approach is to implement an event listener:

<button id="btn2">Click Me</button>

<script>
     const btn2 = document.getElementById("btn2");
     btn2.addEventListener("click", event => { 
          // Perform some action
          return result;
     })
</script>

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

Converting the data in this table into an array of objects using JavaScript

Trying to transform the source table data into a grouped format. https://i.sstatic.net/I7PsO.png Desired grouped data structure: https://i.sstatic.net/xP2Ow.png Transformed the source table into an array of objects representing rows and columns. [ { r ...

Using importNode in the context of Microsoft Edge involves transferring a

I am facing an issue with a dynamic page that has the ability to change its main div content using a bar button. The pages are mostly static except for one which contains JavaScript (RGraph charts). To make it work, I am currently using the following code ...

Bespoke String Implementation

Can someone help me find a dual approach? I am interested in customizing strings based on type. I want to be able to determine the type of a string different from a primitive string during runtime. Take a look at this code: class TZDatabaseName extends ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

When utilizing *array.push(function(parameter))* in Angular/JavaScript, ensure to adjust the object being pushed into the array

Is it possible to modify the object that is pushed into an array using a function within the push method? I have a method that searches for a match between profile.id and keywordId, and then pushes the matching keywordId into an array. How can I update th ...

Incorporate a fresh attribute into each JSON object within a JavaScript array

Currently, my focus is on a react application where I am retrieving a JSON response from a specific route that consists of a collection of JSON objects. My objective now is to introduce a new field in each JSON object based on another field within the sam ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...

Value of variable is not present

My goal is to populate a <select> dropdown with <option> elements on a website using Classic ASP/VBScript. The values are retrieved from an SQL Server Database and the code for this process looks like: SET rows = dbc.execute(SQL) IF NOT ro ...

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

Displaying text within an HTML table featuring a vibrant background

I'm having trouble printing a basic certificate that is formatted as an HTML table. There are a couple of frustrating issues I'm facing. 1) When I try to print the table using Chrome, my CSS changes are not being applied. 2) I can't seem to ...

Having trouble passing an array from PHP to JavaScript

I'm facing an issue with the following code snippet: <?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?> <?php $resultAM = joi ...

State dropdown in Angular dynamically updates based on the country selected

I am in search of a contextual state dropdown menu that is linked to the country, ensuring only relevant states are displayed. I have explored these two solutions for guidance in my project. Angularjs trigger country state dependency angularjs dependant ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

XMLHTTP is not accessible in the Department of Health

My D.O.H framework is powered by nodejs, specifically version 1.10. While I understand that nodejs typically uses xmlhttprequest or other modules for XHR requests, in my scenario, I am opting to utilize Dojo's xhr instead. Unfortunately, it seems tha ...

Issue with jQuery: Changing colors does not work on Chrome and Safarirowsers

I'm puzzled as to why the code snippet below only works in Firefox, but not in Chrome and Safari. Can you shed some light on this issue? if ($(this).css("color") == "Fuchsia"){ $(this).css("color","#000000"); } Here is the link in question: If you ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

Is a DOM lookup performed each time Vue's ref is utilized?

Exploring the capabilities of Vue.js, I have integrated a few refs into my current project. However, I am curious about the efficiency of calling refs in methods. Does Vue perform a DOM lookup every time a ref is called, or does it store all refs once for ...

What could be the reason behind the malfunctioning of my media query in the

I am trying to connect an external stylesheet to my React component in order to apply different styles based on screen width. Specifically, when the screen width is less than 300px, I want the logo to have a height of 100vh. However, it seems that the medi ...