What is the best way to use JavaScript to show a text value alongside radio buttons?

Currently, I am in the process of creating an e-commerce platform that allows customers to choose custom components for their purchases. Although I am relatively new to JavaScript, I have successfully developed a radio button list where the prices are totaled from each section.

One feature that I am looking to add is a box that displays all of the selected options individually, rather than just showing the final total price.

In my existing code, I have utilized text with values and utilized parseInt. However, I am seeking an alternative method to retrieve the text value, as opposed to the numerical value.

This is how my code looks so far:

<head>
    <script type="text/javascript">
        function DisplayPrice(price){
                        var val1 = 0;
                        for( i = 0; i < document.form1.part.length; i++ ){
                                if( document.form1.part[i].checked == true ){
                                        val1 = document.form1.part[i].value;
                                }
                        }

                        var val2 = 0;
                        for( i = 0; i < document.form2.part2.length; i++ ){
                                if( document.form2.part2[i].checked == true ){
                                        val2 = document.form2.part2[i].value;
                                }
                        }

                        var val3 = 0;
                        for( i = 0; i < document.form3.part3.length; i++ ){
                                if( document.form3.part3[i].checked == true ){
                                        val3 = document.form3.part3[i].value;
                                }
                        }


                        var sum=parseInt(val1) + parseInt(val2) + parseInt(val3);
            document.getElementById('totalSum').value=sum;
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" runat="server">
       <br>
       <input id="rdo_1" type="radio" value="0 1.8ghz2xAMD" name="part" checked="checked" onclick="DisplayPrice(this.value);">1.8Ghz Dual Core AMD
        <br>
        <input id="rdo_2" type="radio" value="50 2ghz2xAMD" name="part" onclick="DisplayPrice(this.value);">2Ghz Dual Core AMD
        <br>
    </form>Choose your memory:<br />
    <form name="form2" id="form2" runat="server">
        <br>
        <input id="rdo_1" type="radio" value="0 1333corsair1gb" name="part2" checked="checked" onclick="DisplayPrice(this.value);">1333 Corsair 1GB
        <br>
        <input id="rdo_2" type="radio" value="50 1333corsair2x1gb" name="part2" onclick="DisplayPrice(this.value);">1333 Corsair 2x1GB
        <br>
    </form>Choose your graphics card:<br />
    <form name="form3" id="form3" runat="server">
        <br />
        <input id="rdo_1" type="radio" value="0 5830ATI1gb" name="part3" checked="checked" onclick="DisplayPrice(this.value);">1GB ATI 5830
        <br />
        <input id="rdo_2" type="radio" value="50 5850ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5850
        <br />
        <input id="rdo_3" type="radio" value="75 5870ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5870
        <br />
    </form>
</body>

I appreciate any guidance you can provide on this matter.

Answer №1

It appears that the values are consistently separated by a space. One option is to utilize the split() function in order to divide the value into two parts, with the first part containing the price and the second part containing the text.

const parts = value.split(" ");
const price = parseInt(parts[0]);
const text = parts[1];

Of course, there are more elegant solutions available for achieving the same functionality, but for now, this can serve as a useful learning exercise.

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

Unable to use the same hexadecimal HTML entity in the value props of a React JSX component

Can someone explain why this code snippet displays dots as password and the other displays plain hexadecimal codes? <Field label="Password" value="&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;" type="password" /> While this one disp ...

How to send arguments to an external JavaScript file with JavaScript

In the header of my HTML document, I have included the following script: <script src="http://www.domain.com/js/widgets.js" type="text/javascript"></script> This script references: widgets.js (function () { var styleEl = document.create ...

Getting the selected item from a dropdown menu and including it in an email

While working in React, I have successfully created a contact form that includes fields for name, email, and a message box. When the form is submitted, these three items are sent as expected. However, I am facing difficulty in sending a selected item from ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

Express backend not receiving form data from post request

I recently created a form to submit a file to an express backend, but I'm encountering an issue where the data is not being received on the backend when the form is submitted. Upon using console.log, I noticed that req.body returns {}, and sampleFile ...

Exploring Angular and Node.js to Retrieve Image Dimensions

I'm struggling to figure out the most effective method for determining the image dimensions or naturalWidth of images based on their URL, usually found in the src attribute of an <img> tag. My objective is to input a URL of a news article and u ...

When nightwatch injects JavaScript, it fails to refocus on the subsequent element within the webpage

It's taking a long time to enter over 300 characters using nightwatch's setValue function since it keys in each character individually. I attempted to use the .execute function to inject custom JavaScript onto the page, and while the value is suc ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Step-by-step guide to initializing a project using React with Typescript and a functional server-side script

I am working on a project that involves a React Typescript app (created using Create React App). In this project, I need to have an executable script that can run alongside the React app. Both the app and the script are intended to only run on local machin ...

The error message "React Native Redux useSelector is returning Undefined after navigation" has

After navigating to a new state, I am facing issues with accessing the updated state. Initially, I initialize my dataState in the reducer and update it using actions. On Screen 1, I successfully use this state after dispatching, but when moving to another ...

Javascript - Error encountered when utilizing a for loop to insert a new column into an array

I have been utilizing an API to fetch data on various stocks, and I am attempting to include a column named "symbol" with the query values using the function insertColumn. However, I am encountering an error message that says (node:15732) UnhandledPromiseR ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Sending multiple arguments to a Vuex action

In the Vue Component code snippet below, I have a method: loadMaintenances (query = {}) { this.getContractorMaintenances(this.urlWithPage, query).then((response) => { this.lastPage = response.data.meta.last_page }) } I am trying to pass the par ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

Refresh the React state at regular intervals

constructor(){ super(); this.state={ numbers : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2] }; } componentDidMount(){setInterval(this.updateNumbers(),5000);} updateNumbers() { console.log(this.props.newData); let numbers = this.state.nu ...

Tips for looping through the new element that has been added to an array from the database query result

I am faced with a challenge involving querying a mysql database using each element of an array in Node.js. If a specific condition is met, I need to append additional elements to the same array and iterate through them as well. As I am new to Node.js, I a ...

Utilize the Algolia search-insights library in conjunction with React

Trying to integrate the Search-Insights Library from Algolia with React using npm for installation instead of just adding it to the header as shown in the example. Example of implementation in React Click here for React implementation example <script ...

Generating a new division element with a unique identifier and subsequently making adjustments to it

Just starting out with HTML and JS here, so please excuse my lack of experience and not-so-great English. I have an ID on an HTML element that I want to add content to using a function. Additionally, I need to create another element (inside the first one) ...

Issue with Charts.js: The defined moment is missing when using chart.bundle.min.js

I successfully created a chart with charts.js and configured it, but now I aim to make the X Axis represent time. However, when attempting to implement this using the code below, I encounter the following console error: Uncaught ReferenceError: moment is n ...