derive values from radio group inputs

Attempting to compute a selection value based on a radio group and values from additional fields. Any input in the 'Name' field contributes a value to the Total. The value from the radio group needs to be added to this total. Below is the HTML code:

<FORM NAME="testauthorization" ACTION="" METHOD=POST id="exhibitreg">
  <table>
    <tr>
      <td><label>
          <input type="radio" name="sponsorship" value="3000" id="sponsor1" />
          $3,000</label>
        <br />
        <label>
          <input type="radio" name="sponsorship" value="1500" id="sponsor2" />
          $1,500</label>
        <br />
        <label>
          <input type="radio" name="sponsorship" value="1000" id="sponsor3" />
          $1,000</label>
        <br /></td>
    </tr>
    <tr>
      <td>Name 1 <INPUT NAME="Name_1" TYPE="TEXT" id="name1" onchange="updatecost(1, 50)" onkeyup="updatecost(1, 50)" VALUE="" size="30"></td>
      <td><INPUT NAME="cost_1" TYPE="TEXT" VALUE="" size="4" id="cost1"></td>
    </tr>
    <tr>
      <td>Name 2<INPUT NAME="Name_2" TYPE="TEXT" id="name2" onchange="updatecost(2, 50)" onkeyup="updatecost(2, 50)" VALUE="" size="30"></td>
      <td><INPUT NAME="cost_2" TYPE="TEXT" VALUE="" size="4" id="cost2"></td>
    </tr>
    <tr>
      <td>Name 3<INPUT NAME="Name_3" TYPE="TEXT" id="name3" onchange="updatecost(3, 50)" onkeyup="updatecost(3, 50)" VALUE="" size="30"></td>
      <td><INPUT NAME="cost_3" TYPE="TEXT" VALUE="" size="4" id="cost3"></td>
    </tr>
    <tr>
      <td colspan="4">Total:
        <INPUT NAME="Total" id="Total" TYPE="TEXT" VALUE="" size="8" onFocus="this.form.elements[0].focus()" >
        <INPUT TYPE="HIDDEN" onchange="totalcost()" onkeyup="totalcost()"></td>
    </tr>
  </table>
  <INPUT TYPE="SUBMIT" VALUE="Submit">
  <input type="RESET" name="Reset" value="Reset" />
</FORM>

Here is the JavaScript:

<script language="JavaScript" type="text/javascript">
function getRadioValue(name) {
    var group = document.getElementsByName('sponsorship');
    for (var i=0;i<group.length;i++) {
        if (group[i].checked) {
            return group[i].value;
        }
    }
    return '';
}

function updatecost(num, dollars) {
    var text = document.getElementById("name" + num);
    var cost = document.getElementById("cost" + num);
    if (!text) return;
    if (!cost) return;
    if (text.value == "") {
        cost.value = "";
    }
    else {
        cost.value = dollars;
    }
    totalcost();
}
function totalcost() {
    var total = 0;
    for (var i = 1; i <= 3; i++) {
        var cost = document.getElementById("cost" + i);
        if (cost.value) total += Number(cost.value);
    }

    document.getElementById("Total").value = total;
}
</script>

Is there something missing here? Just to clarify, I am relatively new to JavaScript, so any constructive feedback to improve my understanding is appreciated. Keeping it simple is key for me. Thank you!

Answer №1

Revise the following function to replace the existing one

    function modifycost(num, dollars) {
        var text = document.getElementById("name" + num);
        var cost = document.querySelector('input[name="sponsorship"]:checked');
        if (!text) return;
        if (!cost) return;
        calculateTotal(cost);
    }
    function calculateTotal(cost) {
        var total = 0;
        for (var i = 1; i <= 3; i++) {
            var text1 = document.getElementById("name" + i);
            if (text1.value != "") total += Number(cost.value);
        }
        document.getElementById("Total").value = total;
    }

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

Named Graph's Title on Image Save in Echarts

Is there a way to give a title to the image graph saved in Echarts, as Echarts does not have this option available? Any suggestions on how we can achieve this? Here is a link for reference from Echarts that provides the 'saveAsImage' option: Ch ...

What can I do to prevent my panolens.js image from pausing its spin whenever a user clicks on it?

I've been working on setting up a 360 image background that rotates automatically and disabling most user interaction controls. However, I'm struggling with one issue – preventing any form of interaction from the user altogether. Whenever a use ...

How can I retrieve a global variable in Angular that was initialized within an IIFE?

I'm a beginner in Angular, so I ask for your patience. Currently, I am in the process of migrating an app from Asp.net MVC5 to Angular. One of the key functionalities of this application involves connecting to a third-party system by downloading a Jav ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

Problem encountered when attempting to post to a node/express endpoint

It has been a while since I last used JQuery/Ajax instead of axios to connect to an endpoint, am i making any mistakes here? var express = require('express'); var app = express() var bodyParser = require('body-parser'); var path = re ...

Vitejs is currently loading the entire bundle size instead of just the specific selected files

While working with Vue 3 and Vite, I came across an issue that seems quite strange. The Oh Vue Icons library is loading a massive 108 MB of bundle size, which significantly slows down the loading time even in ViteJS. Here's how my setup looks like: im ...

Why is Reactjs axios returning a promise instead of the expected value?

I have been attempting to retrieve data from an API using axios, but all I am getting back is a Promise. The Node.js code: router.get('/isAdmin/:userId/:groupeId', async (req, res) => { let userId = req.params.userId let groupeId = ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

Utilizing Mongoose Schema for CSV Import

My current task involves importing a large CSV file into a mongo DB, where the order of the values will determine the key for each entry in the database: Here is an example of the CSV file structure: 9,1557,358,286,Mutantville,4368,2358026,,M,0,0,0,1,0 9 ...

Instructions for adding a new line in a textarea on Internet Explorer when reading from a file

I'm facing a situation where I need to display the contents of a file (let's call it abc.txt) in a textarea on a JSP page. However, when I try to do so, all the contents are displayed in one line without any line breaks or carriage returns. Inte ...

The callback function used for the database query did not provide any results

So here's a code snippet: module.exports.checkEmailInUse = (email) => { connection.query('SELECT `id` FROM `users` WHERE email = ?', [ email ], function(err, rows, fields) { console. ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

What is the process for reading server responses following the delivery of an alert to a designated user through socket.io?

Recently, I started exploring Socket.io and encountered an interesting challenge. My goal is to retrieve real-time location data from an Android device. To achieve this, I developed a basic application to access the current GPS coordinates. Additionally, I ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Show specific button text when no file has been selected

I have a form with an image container that allows users to change the photo. The icon opens a file browser, and when the user selects a file, the Change button submits the photo and updates it. https://i.sstatic.net/R5vwn.jpg If no file is selected, I wa ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Creating Original Tweets using Javascript without Repeating Images

I'm developing a Twitter bot using the Twit NPM package and need assistance on how to avoid posting duplicate images when uploading images to Twitter. The current image_path variable is responsible for scanning through my image directory, but I want ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...