`Calculate sum of dropdown selection values using jQuery`

Currently, I am in the process of developing a form that enables users to select various services and see the total cost displayed. At the moment, I have managed to calculate the running total for one service selected from a dropdown menu. However, I am encountering difficulties in adding up costs from multiple services chosen from different dropdown menus simultaneously. For instance, if a user selects '3' from one dropdown menu, it should be multiplied by 10 (already implemented), and then if they choose '4' from another dropdown menu, it should be multiplied by a specific value and the total cost displayed.

Here is the Fiddle link for reference: https://jsfiddle.net/7jrch7w6/

As someone who is new to JavaScript and JQuery, any suggestions on improving my approach or code quality are welcome. Thank you in advance!

Below is the snippet of the code:

<form>
<div id="carpet-services">
                <div class="form-group">
                    <!--how many bedrooms-->
                    <label class="control-label" for="carpet_cleaning">Bedrooms</label>
                    <select class="form-control" id="carpet_cleaning">
                        <option value="0-bedroom">0</option>
                        <option value="1-bedroom">1</option>
                        <option value="2-bedroom">2</option>
                    </select>
                    <label class="hide" for="0-bedroom">0</label>
                    <label class="hide" for="1-bedroom">1</label>
                    <label class="hide" for="2-bedroom">2</label>
                    <!--how many dining rooms-->
                    <label class="control-label" for="dining_rooms">Dining Rooms</label>
                    <select class="form-control" id="dining_rooms">
                        <option value="0-diningRoom">0</option>
                        <option value="1-diningRoom">1</option>
                        <option value="2-diningRoom">2</option>
                    </select>
                    <label class="hide" for="0-diningRoom">0</label>
                    <label class="hide" for="1-diningRoom">1</label>
                    <label class="hide" for="2-diningRoom">2</label>
     </div>
  </div>

    <h4>Total Price</h4>
      <p id="output1"></p>

JS

    $("#carpet_cleaning").change(function () {
    var bedrooms = $("#carpet_cleaning").val();
    var diningRooms = $("#dining_rooms").val();
    var bedroomPrice = '';
    var diningRoomPrice = '';

    if (carpet_cleaning){
        var bedroomsLabel = $("label[for="+bedrooms+"]").text();
        bedroomPrice = 'Your price quote is: ' + bedroomsLabel * 10;
    }

    $("#output1").text(bedroomPrice).fadeIn();
});

One line of CSS: label.hide {display: none;}

Answer №1

When creating drop down options, it's unnecessary to use labels for each one as the value attribute serves that purpose:

<form>
    <div id="carpet-services">
                    <div class="form-group">
                        <!--how many bedrooms-->
                        <label class="control-label" for="carpet_cleaning">Bedrooms</label>
                        <select class="form-control" id="carpet_cleaning">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                        </select>
                        <!--how many dining rooms-->
                        <label class="control-label" for="dining_rooms">Dining Rooms</label>
                        <select class="form-control" id="dining_rooms">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                        </select>
         </div>
      </div>

        <h4>Total Price</h4>
          <p id="output1"></p>
  </form>

To simplify the calculation and connect it correctly to the change event of both drop downs:

$("#carpet_cleaning,#dining_rooms").change(function () {
        var bedrooms = $("#carpet_cleaning").val();
        var diningRooms = $("#dining_rooms").val();

        var total = bedrooms * 10 + diningRooms * 20;
        var totalPrice = 'Your price quote is: ' + total;

        $("#output1").text(totalPrice).fadeIn();
});

Answer №2

It’s possible that your question wasn’t clear, but you can retrieve the currently selected value in a select element using

$("#carpet_cleaning option:selected").val()
.

Check out this example on JSFiddle: https://jsfiddle.net/7jrch7w6/4/

$("#carpet_cleaning").change(function () {
  UpdateResult();
});

$("#dining_rooms").change(function () {
    UpdateResult();
});

function UpdateResult()
{
    var result = 'Your price quote is: ' + (($("#carpet_cleaning option:selected").val() * 10) + ($("#dining_rooms option:selected").val() * 20))
    $("#output1").text(result).fadeIn();
}

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

Struggling to superimpose my navigation bar onto the title page background

I'm currently learning HTML and CSS on my own while I am in university. My current project involves creating a one-page website, but I am having difficulty positioning the navigation bar over the title page. My goal is for the navigation bar to remai ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Is there a way to find the Nth occurrence of a specific weekday in each month between two given dates using JavaScript?

Within my program, users can set events with start and end dates, as well as the period of repetition: weekly, monthly by date, monthly by weekday, or yearly. Once an event is created, it's stored in the database and displayed on the main calendar pag ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Adjusting the desktop view through media queries for mobile devices

As someone with no coding experience, I've been working on my portfolio using Cargo. Currently, I'm trying to adjust the mobile view of an article on my homepage through media queries. However, the code is unintentionally changing the layout on d ...

Concentrate on implementing Cross-domain Ajax functionality in Opera browser

For a unique and interesting browsing experience, try using Opera 9.62 to explore the nuances of cross-sub-domain JavaScript calls with Ajax. To understand this better, follow these instructions by placing three simple files on appropriate domains. foo.ht ...

Please define a unique "redirect_uri" in the FB.ui() function for posting purposes

I'm currently utilizing the "Facebook Javascript Sdk" to publish messages on a user's wall. However, I am facing an issue with dynamic redirect URLs. Even though I am explicitly passing the "redirect_uri" as a link with query string in the FB.ui ...

The combination of loading and scrolling JavaScript code is not functioning properly on the website

I created an HTML webpage that includes some JavaScript code to enhance the user experience. However, I encountered an issue when trying to incorporate a load JavaScript function alongside the scroll JavaScript function on my page. The load script is posi ...

Unable to locate the MoreVert icon in Material UI interface

I am trying to incorporate the MoreVert icon into my application's header to display signout and settings options. I have added the MoreVert icon as shown below, and although the popup appears when clicking on the supposed location of the icon, I am u ...

Checking Date and Time in JavaScript

I'm struggling with validating a date time string in Javascript, based on the language set in the browser. For example, if the language is set to pt-BR, the format would be dd/MM/yyyy HH:mm:ss I attempted to use the following code: var dateFormat ...

Creating a hierarchical JSON structure using a database query in JavaScript

Currently, I am in the process of building a nested JSON object by parsing a query string obtained from an SQL database. This constructed JSON object will then be utilized by Angular to display data in the user interface using angular2-query-builder. The ...

The $POST method is failing to update the information

I've encountered an issue with my script that I can't seem to figure out. After numerous tests, it seems like the main problem lies within the Ajax request. Interestingly, I have used the Ajax request successfully in a previous version of my scri ...

Oops! Looks like we're missing some vital information (Could the User input object from angular not be reaching node?). Both data and

Exploring the world of MEAN stack with basic applications and tutorials has been my recent endeavor. Currently, I am working on capturing user input from a registration form using Angular and encrypting passwords using bcrypt. Interestingly, despite loggin ...

Issue with bottom margins or padding

I am a beginner and I have noticed some black space at the bottom of my page. Unfortunately, using margin-bottom to remove it doesn't work as expected. When scrolling down, there is this pesky black space that I want to get rid of. Any help would be a ...

The API functions properly in Postman, however, encountering issues when integrated into the frontend of a React

I am currently working on an ecommerce project using the MERN stack for practice. Being new to the Mern stack, everything is running smoothly except for the "UpdateCategory" functionality in the frontend section. Interestingly, it functions perfectly in PO ...

What is the best way to obtain the final visible element using jQuery?

Could you please check out the following link: http://jsfiddle.net/SHfz4/ All of the blue boxes are technically visible, so I can't use the code $('.row .inner .item:visible:last'); as it will always return box 27. Some boxes may not be v ...

What is the best way to link a single post to a collection of posts?

I am currently working on building a basic blog using PHP. My goal is to create a link from a post to a list of all posts on the blog, similar to the example shown below: Example of how I plan to display posts and a post viewer There are two distinct par ...

"Radio buttons within ngFor loop do not allow for deselecting options

As I work on creating a quiz, I've encountered an issue with the radio buttons not functioning correctly. When clicked, they do not unmark themselves when clicked again or when another option is selected. The value of the last clicked option is passed ...

Unable to retrieve any response data in Angular 2

I'm having trouble retrieving the response from my API. Despite being able to do so with PostMan, my variable "this.data" remains null. I've experimented with various approaches to no avail. Any assistance would be greatly appreciated. The method ...