Using jQuery to determine if a radio button has been selected on a price calculator

Having a JavaScript code that calculates the total price based on radio/checkbox selection.

JQUERY

var price = 0;
$('.price-input').click(function () {
    if ($(this).is(":checked")) {
        price += parseInt($(this).attr("data-price"), 10);
        $('.total-price').text(price);
        $('.total-price-input').val(price);
    } else {
        price -= parseInt($(this).attr("data-price"), 10);
        $('.total-price').text(price);
        $('.total-price-input').val(price);
    }
});

The HTML consists of 3 radiobuttons and 3 checkboxes. The radiobutton has a set price, while the checkboxes can add their prices to the selected radiobutton for a total price calculation.

<input class="price-input" data-price="2000" id="ChosenLane" name="ChosenLane" type="radio" value="Conference - Track 1: Lean">
<input class="price-input" data-price="1300" id="ChosenLane" name="ChosenLane" type="radio" value="Conference - Track 2: Innovation">
<input class="price-input" data-price="1600" id="ChosenLane" name="ChosenLane" type="radio" value="Cake">

<input type="checkbox" name="lanes" value="Evening buffet" data-price="1000" class="price-input">
<input type="checkbox" name="lanes" value="xyz" data-price="5456" class="price-input">
<input type="checkbox" name="lanes" value="abc" data-price="54545" class="price-input">

The current setup adds the price each time a radiobutton is clicked, even if it's already selected. I want the radiobuttons to use just their own price when selected, without adding multiple times to the total.

For example, selecting a radiobutton should add its specific price to the total. If another radiobutton is selected, it should subtract the previous price and add the new one.

Answer №1

Kindly review the solution provided below:

JAVASCRIPT

$(document).ready(function() {
    $('.price-input').change(function() {
        var price = 0;
        $('.price-input').each(function(){
            if ($(this).is(":checked")) {
                price += parseInt($(this).attr("data-price"), 10);
            }
        });
        $(".totalPrice").text(price);
    });
});

Fiddle: http://jsfiddle.net/kkqqfaqv/

Answer №2

To update your code, switch the event from click to change. Click events occur every time a user clicks on the radio button, regardless of whether it is selected or not. On the other hand, a change event will only be triggered when the state of the checkbox actually changes.

Answer №3

I'm a bit uncertain about the connection between price and total-price-input in your situation.

To ensure greater reliability, it's best not to solely rely on removing and adding values one by one. It's more advisable to:

  • Begin your callback function with price=0
  • Determine which input buttons and radio buttons are selected
  • Add up the values accordingly

This approach also allows you to set up a clean slate callback after the page has loaded: If a user navigates forward and then back, their previous selections will still be intact (in most modern browsers) instead of starting over at 0 due to a "refresh problem." To achieve this, create a separate named function to call within $.ready() and .change().

Additionally, I recommend using .change() rather than .click() as inputs can change state through methods other than click events (such as keyboard navigation), and 'change' is the event you want to capture.

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

Attempting to trigger an action from a Vuex module proves futile as the error message "[vuex] unknown action type" is generated

I've been struggling to successfully register a Vuex module. Below is the code I've been working with: stores/index.js: import Vuex from 'vuex'; import resourcesModule from './resources'; import axios from '@/helpers/ax ...

Steps to retrieve the chosen dropdown menu in the edit model using Laravel

I'm working on a Laravel project where I can retrieve data from the database into my modal. However, every time I update the modal, the option values in both select fields increase with the fetched result. How do I prevent this from happening? Below a ...

What is the best way to identify the appropriate class name for searching in Selenium?

I'm currently on a mission to find an element based on its class name. I have extracted this snippet from the page source (which I saved as a file using BeautifulSoup): <div class="flex flex-column"><div... If I attempt to pinpoin ...

Executing Ajax invokes a PHP script which inserts data into MySQL database; interested in viewing any PHP error messages

Utilizing jquery, I am making an Ajax call to execute a php script for inserting data into a MySQL database. Everything functions smoothly on php7. However, while testing the code on php8, I encounter an error within the error function. An error seems to ...

How can CSS be used to center multi-line text with the shortest line appearing at the top

I'm currently working on some html and css code that looks like this: <div style="width: 40em; text-align: center;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard du ...

Extracting and retrieving information from a complex data structure obtained through an API call

Struggling with this one. Can't seem to locate a similar situation after searching extensively... My goal is to determine the author of each collection associated with a user. I wrote a function to fetch data from an API for a specific user, in this ...

Exploring JSON Array Data and Its Sub-Properties in React

I have a JSON array containing personal data that I want to access from my React app. This JSON file is already included in my React application. { "person": [ { "id": "userId", "sellerImage": "https://i.pravatar.cc/300", ...

Is it possible to utilize JavaScript for displaying a continuous stream of images?

In this scenario, you are tasked with working with an image API and need to send a POST request to retrieve an image stream for display on the rest of your webpage. While I am able to use jQuery to make an ajax request to the service upon page load, I am ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

Is it possible to utilize the event load function while offline with a text file?

Is there a way to load a div that I have saved as plain text (in a file)? The file is located in the same root directory as my HTML page. I am attempting to call this file using jQuery's event load on my HTML page like this: $("#tab2").load("textfile ...

Utilizing Python's Requests Library to Submit a Form without Specifying Input Names

My task is to perform a POST request using the Python Request module. However, I am facing an issue where the input I need to work with only has an id attribute and no name attribute. Most of the examples I have come across involve using the name attribute ...

Div with absolute positioning not aligned correctly on Mac/iOS but displays correctly on Windows

Struggling with this issue for a few days now and I can't seem to pinpoint the cause. After some online research, it seems like a collapsing margin bug might be the culprit, but I'm hoping to get a clear answer or at least some guidance. I have ...

Getting the Correct Information from Upload Files in jQuery and PHP

While experimenting with the jquery plugin called jquery.filer, I encountered an issue during file upload on their official website . The returned value I received looked like this: { "files": [ "..\/uploads\/dK079QrL2g.docx" ], "metas": [ ...

Executing a C++ application within a web browser

I'm looking to integrate my C++ program that generates random sentences from a word bank into my personal, low-traffic website. Ideally, visitors could click a button and see a new sentence displayed on the page. What would be the easiest way to accom ...

Determining the worth of radio buttons, dropdown menus, and checkboxes

I am working on designing a menu for a pizza place as part of a learning project. The menu allows users to select their pizza size from small, medium, and large using radio buttons, and then customize it further with three select boxes where each selection ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

Displaying both items upon clicking

Hey there, I'm having an issue where clicking on one article link opens both! <span class='pres'><img src='http://files.appcheck.se/icons/minecraft.png' /></span><span class='info'><a href=&apo ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Is it feasible to exclusively apply Twitter Bootstraps .navbar-fix-to-top on mobile devices?

I am working on a website using Twitter Bootstrap 3 and I have implemented the following navbar: <div class="col-xs-12 col-md-10 col-md-offset-1"> <nav class="navbar navbar-inverse" role="navigation"> <div class="navbar-header"> ...