Find total of dropdown selection values with jquery - javascript

I'm creating a form that allows a user to select an amount of services, and then a total is displayed. I have it working to where I can keep the running total of one drop down menu service, but then I can't figure out how to add additional services from other drop down menus. For example, I need it so that if someone selects '3' from one drop down menu, it will times that value by 10 (I have that part done), but then also be able to select a '4' from the next dropdown menu and times that by a value, and then display a total.
Fiddle: https://jsfiddle.net/7jrch7w6/
I'm very new to JavaScript and JQuery, so feel free to give suggestions if you see a better way or if my code is garbage. Thanks!
Here's my 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;}

First of all, there's no need to use labels for every drop down option, that's what value attribute is for:
<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>
Calculation can now be simplified and properly hooked up to 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();
});

I don't know if I got your question, but you can use $("#carpet_cleaning option:selected").val() to get the current selected value in a select component.
Fiddle: 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();
}

Related

How to combine Selected price and input checkbox price Jquery?

i have a checkout form . where there are 2 fields are used o give total amount of checkout . 1 field is in select tag and second is input type check box i want when i select and option and checkbox there values should be combine to give total.
$(function() {
$('.price-input').change(function() {
var price = 0;
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
})
$("select.price").change(function() {
var selectedPrice = $(this).children("option:selected").val();
document.getElementById("totalPrice").innerHTML = selectedPrice;
});
$(".totalPrice").text(price);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">#lang('Number of Words'):</label>
<select class="price" name="word_prices_id" required>
<option value="">#lang('Select Words')</option>
#foreach($wordPrice as $wPrice)
<option value="{{$wPrice->id}}">{{$wPrice->page_quantity}} words</option>
#endforeach
</select>
</div>
</div>
<input class="price-input" type="checkbox" name="upsell" value="12">
I added a class .ajx to both Select and input to handle changes made on both of their values in the same function !
$(document).on('change', '.ajx', function () {
if ($( "input.price-input:checked" ).is(":checked") && $("select.price").val()!==''){
var price = 0;
price += parseInt($("select.price").val(),10);
$('.price-input').each(function() {
if ($(this).is(":checked")) {
price += parseInt($(this).attr("value"), 10);
}
});
$(".totalPrice").empty().text(price);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Price:</label>
<select class="price ajx" name="word_prices_id" required id="exampleFormControlSelect1">
<option value="">Choose Price</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
<input class="price-input ajx" type="checkbox" name="upsell" value="12">
<input class="price-input ajx" type="checkbox" name="upsell1" value="15">
<div class="totalPrice">
</div>

populate select box on previous select and with clone

I am trying to add cloning functionality for select boxes.
I have 3 select box: country, state, city and first user select the country and on id basis state select box is populated with options and same with city dropdown will populate only when state is selected.
Then I have add more option where I have regenerate everything. so I am cloning my div but the problem when I change my country instead of showing new state dropdown its returns to previous drop down:
$('.country').on('change',function(){
var id = $(this).val();
callAjax(id);
});
$('.state').on('change',function(){
var id = $(this).val();
callAjax(id);
});
$('#btClone').on('click', function () {
$('#country')
.clone()
.attr('id', 'country_' + i)
.attr('name', 'country_' + i)
.appendTo("#container2");
$('#state')
.clone()
.attr('id', 'state_' + i)
.attr('name', 'state_' + i)
.appendTo("#container2");
i =i+1;
});
My Html looks like
<div id="container1">
<select id="country" name="country" class="hidden country">
</select>
<select id="state" name="state" class="hidden state">
</select>
<select id="city" name="city" class="hidden city">
</select>
<span id="selected-profile"></span>
<div id="addons" class="hidden">
<input type="button" id="btClone" value="Clone the list" style="float:right;" />
</div>
</div>
<div id="container2" style="display:none;"></div>
I want when i click on add new then chose country then change something my ajax call again call but as of now i am unable to do that because i already have options
what exactly do you mean with "instead of showing new state dropdown its returns to previous drop down". I tried your code in a fiddle and it's cloning as expected.
function initRow($row){
$row.find('select[name="country"]').on('change', function () {
var thisRow = $(this).closest('div.row');
var stateDD = thisRow.find($('select[name="state"]'));
stateDD.show();
stateDD.on('change',function(){
var cityDD = thisRow.find('select[name="city"]');
cityDD.show();
cityDD.on('change',function(){
});
});
});
}
$('#container1 .row').each(function(){
initRow($(this));
});
$('#btClone').click(function(){
var rowTemplate = $('#container1 > .row').eq(0).clone();
rowTemplate.find('select[name="state"]').hide();
rowTemplate.find('select[name="city"]').hide();
initRow(rowTemplate.appendTo($('#container1')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container1">
<div class="row">
<select name="country" class="hidden country">
<option value=1>country 1</option> <option value=2>country 2</option>
</select>
<select name="state" class="hidden state" style="display:none;">
<option value=1>state 1</option> <option value=2>state 2</option>
</select>
<select name="city" class="hidden city" style="display:none;">
<option value=1>city 1</option> <option value=2>city 2</option>
</select>
</div>
</div>
<input type="button" id="btClone" value="Clone the list" style="float:right;" />

Show/hide divs based on values selected in multiple select2 dropdowns

I am building a search result filtering feature. I have a number of select2 dropdown boxes where the user can select multiple values from to either hide or show divs with matching class values. I have a number of divs with classes containing values matching values in the select2 dropdown boxes. How do I go about coding this functionality?
I can only get this to work for one selection, I'd like to be able to select multiple options from the dropdowns.
$('select.filterCandidates').bind('change', function() {
$('select.filterCandidates').attr('disabled', 'disabled');
$('#candidates').find('.row').hide();
var critriaAttribute = '';
$('select.filterCandidates').each(function() {
if ($(this).val() != '0') {
critriaAttribute += '[data-' + $(this).data('attribute') + '*="' + $(this).val() + '"]';
}
});
$('#candidates').find('.row' + critriaAttribute).show();
$('#filterCount').html('Showing ' + $('div#candidates div.row:visible').length + ' Matches');
$('select.filterCandidates').removeAttr('disabled');
});
$('#reset-filters').on("click", function() {
$('#candidates').find('.row').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<br>
<h4>Search Form</h4>
<br>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="type" class="form-control filterCandidates" data-attribute="type">
<option value="0">Candidate Type</option>
<option value="CA">CA</option>
<option value="CFA">CFA</option>
<option value="CFO">CFO</option>
<option value="CIMA">CIMA</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="role" class="form-control filterCandidates" data-attribute="role">
<option value="0">Preferred Role</option>
<option value="Analyst">Analyst</option>
<option value="Associate">Associate</option>
<option value="CFO">CFO</option>
<option value="FD">FD</option>
<option value="FM">FM</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="roleType" class="form-control filterCandidates" data-attribute="roleType">
<option value="0">Preferred Role Type</option>
<option value="Permanent">Permanent</option>
<option value="Contract/Interim">Contract/Interim</option>
<option value="Internship">Internship</option>
</select>
</div>
</div>
</div>
just to give you a rough idea as you have not provided any code.
<script>
var SelectedValues = $('#ddlSelect option:selected');
var NotSelectedValues $('#ddlSelect option:not(:selected)');
$(SelectedValues ).each(function () {
$("."+$(this).val()+"").show(); //show all those divs containing
//this class
});
$(NotSelectedValues ).each(function () {
$("."+$(this).val()+"").hide();//hide all those divs containing
//this class
});
</script>
This is a rough idea , The above script will show all of the divs containing the classes you have selected in your select2 with id "ddlSelect" and hide those which you have not selected.
you can put this into a function and call it on onchange event of ddlSelect or whatever and however you want it to.

Jquery Select field populates Input field

I am trying to Select one of the options from the drop-down and populate the input field with the correct values.
I want to set the value 1 to ($100) val 2 to ($200)
I will not have access to a database to store the values.
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name=
"costfield">
<option value="Select Country"> Select Country</option>
<option value="1"> country 1</option>
<option value="2"> country 2</option>
<option value="1"> country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="estimate" class="form-control" id="exampleInputEstimate1" placeholder="Estimate">
</div>
</div>
<script>
$( "#costfield" ).val();
$( "#estimate" ).text( "this" ).show();
</script>
</div>
You can store the values in the HTML5 data- attribute for each <option> element. This approach is useful when there is no direct relationship between the option's value attribute and the dollar value you are assigning it to.
p/s: type="estimate" is not a valid attribute value. Try type="text" (anyway, browsers will parse invalid type into text automagically.
// Listen to change
$('#costfield').change(function() {
$('#exampleInputEstimate1').val($(this).find('option:selected').data('dollar-value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name="costfield">
<option value="Select Country">Select Country</option>
<option value="1" data-dollar-value="$100">country 1</option>
<option value="2" data-dollar-value="$200">country 2</option>
<option value="1" data-dollar-value="$100">country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="exampleInputEstimate1" placeholder="Estimate" />
</div>
$('[name="costfield"]').change(function () {
console.log("test");
var cost = this.value;
var str = "";
switch (cost) {
case "1":
str = "$100";
break;
case "2":
str = "$200";
break;
}
$("#exampleInputEstimate1").val(str);
});
JSFiddle
You could use jQuery to get the value from the Select when it changes and then change the value of the input accordingly. So put this in between the script tags.
$('#costfield').on('change', function() {
var value = $(this).val();
$('#exampleInputEstimate1').val(value);
});
You can either set your option values to be 100 or 200 then on any change in the drop down set the value of your input to the value.
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val());
} );
If you want to keep your option values as they are then you can still use the same as above with a small change. (on the assumption that 1 will be 100, 2 will be 200, 3 will be 300, and so on)
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val() + "00" );
} );
Also you may want to put a new option and set it as blank with no value that way you force the user to select something. Or you can set the input on document load and keep the number of options you have. AKA:
<option value="" ></option>

How to show specific content based on 3 drop down selections?

I would like to display a div depending on a user's selection from two drop down lists.
While I'm going to display 3 dropdown options to the users, I'm only going to generate the output based on the selection of the first two:
This means that I will have a total of 9 possible outputs based on the user's selection:
Beaches --> Chill
Beaches --> Fast-Paced
Beaches --> Both
Museums --> Chill
Museums --> Fast-Paced
Museums --> Both
Mountains --> Chill
Mountains --> Fast-Paced
Mountains --> Both
Just for similar reference, a few months ago, I used the following script to generate a specific output based on 2 drop down selections:
http://jsfiddle.net/barmar/ys3GS/2/
<body>
<h2>Find your Animal Name</h2>
<p>Select your birth month and your favorite color and find your animal name.</p>
<form>
<select id="month">
<option value="">- birth month -</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<label class="January" for="January">January Name</label>
<label class="February" for="February">February Name</label>
<label class="March" for="March">March Name</label>
<label class="April" for="April">April Name</label>
<label class="May" for="May">May Name</label>
<label class="June" for="June">June Name</label>
<label class="July" for="July">July Name</label>
<label class="August" for="August">August Name</label>
<label class="September" for="September">September Name</label>
<label class="October" for="October">October Name</label>
<label class="November" for="November">November Name</label>
<label class="December" for="December">December Name</label>
<select id="color">
<option value="">- favorite color -</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Red">Red</option>
</select>
<label class="Green" for="Green">Green Name</label>
<label class="Blue" for="Blue">Blue Name</label>
<label class="Red" for="Red">Red Name</label>
</form>
<p id="output"></p>
</body>
But this need is a little different. Any thoughts on how I can achieve this? In other words – once the user selected the two options, I want the corresponding div (out of the 9 options) to show up below.
Thanks so much!
You can create 9 div elements and each div element will have two data attributes. One for travel preference and one for style. Like so:
<div class="result" data-preference="beaches" data-style="chill"></div>
<div class="result" data-preference="beaches" data-style="fast-paced"></div>
<div class="result" data-preference="beaches" data-style="both"></div>
<div class="result" data-preference="museums" data-style="chill"></div>
<div class="result" data-preference="museums" data-style="fast-paced"></div>
<div class="result" data-preference="museums" data-style="both"></div>
<div class="result" data-preference="mountains" data-style="chill"></div>
<div class="result" data-preference="mountains" data-style="fast-paced"></div>
<div class="result" data-preference="mountains" data-style="both"></div>
<style>
.result {display:none;}
.result.active {display:block;}
</style>
Also, let's go ahead and add some CSS to hide these div elements, and then setup an active class so that we can display the div once the user has made their selections.
The select elements where the user makes a choice will have options, and each value will have to be identical to the data-preference and data-style values. When a user has made a selection in both of the dropdowns we'll grab all the div's and filter out the one that has the matching data attributes.
$('#preference, #style').on('change', function(){
// set reference to select elements
var preference = $('#preference');
var style = $('#style');
// check if user has made a selection on both dropdowns
if ( preference.prop('selectedIndex') > 0 && style.prop('selectedIndex') > 0 ) {
// remove active class from current active div element
$('.result.active').removeClass('active');
// get all result divs, and filter for matching data attributes
$('.result').filter('[data-preference="' + preference.val() + '"][data-style="' + style.val() + '"]').addClass('active');
}
});
jsfiddle: http://jsfiddle.net/EFM9b/1/
The following is jQuery will work for any number of select fields. It uses the values of the options as CSS classes which are then used to match against the results boxes.
No hiding or showing of the results happens until all select boxes are chosen.
JSFiddle
http://jsfiddle.net/chnZP/
CSS
#results-container > div { display: none; }
HTML
<div id='select-container'>
<select>http://jsfiddle.net/9Qpjg/15/#update
<option value='none'>Select Option</option>
<option value='alpha'>Alpha</option>
</select>
<select>
<option value='none'>Select Option</option>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
</select>
<select>
<option value='none'>Select Option</option>
<option value='dog'>Dog</option>
<option value='cat'>Cat</option>
</select>
</div>
<div id='results-container'>
<div class='dog red alpha'> Alpha Red Dog</div>
<div class='dog blue alpha'> Alpha Blue Dog</div>
<div class='cat red alpha'> Alpha Red Cat</div>
<div class='cat blue alpha'> Alpha Blue Cat</div>
<div>
JavaScript
jQuery(function($){
var
selects = $('#select-container select'),
results = $('#results-container > div');
selects.change(function(){
var values = '';
selects.each(function(){
values += '.' + $(this).val();
});
results.filter(values).show().siblings().hide();
});
});
Careful naming of your divs will get you most of the way there, e.g.
<div class='itinerary' id="beaches_chill">...</div>
<div class='itinerary' id="beaches_fast-paced">...</div>
...
<div class='itinerary' id="mountains_both">...</div>
Now show or hide these based on your dropdowns:
$('#preference, #style').change(function() {
$('.itinerary').hide();
$('#' + $('#preference option:selected').val() + '_' + $('#style option:selected').val()).show();
});
(Another answer here suggests using attributes--that's nicer than using the id, so do that.)

Categories

Resources