Calculate total price script not working - javascript

I want to calculate the total price and display the subtotal at the bottom of the form, but it's not working and I don't know why.
The subtotal should be showing the total price after substraction or addition of the elements "prijsvolwassenen", "prijskinderen", "prijspeuters" and "prijskamertype"
FIDDLE HERE
this is my script
$(document).ready(function calculatePrice(formclear) {
//Get selected data
var elt = document.getElementById("prijsvolwassenen");
var volwassenen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskinderen");
var kinderen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijspeuters");
var peuters = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskamertype");
var kamertype = elt.options[elt.selectedIndex].value;
//convert data to integers
volwassenen = parseInt(volwassenen);
kinderen = parseInt(kinderen);
peuters = parseInt(peuters);
kamertype = parseInt(kamertype);
//calculate total value
var total = volwassenen+kinderen+peuters+kamertype;
//print value to PicExtPrice
document.getElementById("PicExtPrice").value=total;
}
}
And here is the HTML:
<form name="formclear" action="" method="post" id="bootstrap-frm">
<label>
<span>Volwassenen :</span>
<select class="autowidthselect" name="prijsvolwassenen" onChange="calculatePrice()" id="prijsvolwassenen">
<option value="-50">1</option>
<option selected="selected" value="0">2</option>
<option value="50">3</option>
<option value="100">4</option>
<option value="150">5</option>
<option value="200">6</option>
<option value="250">7</option>
<option value="300">8</option>
</select>
</label>
<label>
<span>Kinderen (4-12 jr) :</span>
<select class="autowidthselect" name="prijskinderen" onChange="calculatePrice()" id="prijskinderen">
<option value="-50">0</option>
<option value="-25">1</option>
<option selected="selected" value="0">2</option>
<option value="25">3</option>
<option value="50">4</option>
<option value="75">5</option>
<option value="100">6</option>
<option value="125">7</option>
</select>
</label>
<label>
<span>Kinderen (0-3 jr) :</span>
<select class="autowidthselect" name="prijspeuters" onChange="calculatePrice()" id="prijspeuters">
<option selected="selected" value="0">0</option>
<option value="15">1</option>
<option value="30">2</option>
<option value="45">3</option>
<option value="60">4</option>
<option value="75">5</option>
<option value="90">6</option>
<option value="105">7</option>
</select>
</label>
<label>
<span> Kamertype :</span>
<select class="autowidthselect" name="prijskamertype" onChange="calculatePrice()" id="prijskamertype">
<option selected="selected" value="selecteer kamertype">Selecteer kamertype</option>
<option value="295">Kraaiennest</option>
<option value="395">Kajuit</option>
<option value="495">Kapiteinshut</option>
</select>
</label>
<label>
<button type="button" onclick="calculatePrice()">Calculate</button>
</label>
<label>
<span>Subtotaal: </span>
<input id="PicExtPrice" type="text" size="10"/>
</label>
</form>

You are actually mixing up things there. You tried to use document ready that's part of the jQuery library (which you're not loading nor using anywhere in your code), when actually you just needed to declare a function.
This script should work for you:
<head>
<script type="text/javascript">
function calculatePrice() {
//Get selected data
var elt = document.getElementById("prijsvolwassenen");
var volwassenen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskinderen");
var kinderen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijspeuters");
var peuters = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskamertype");
var kamertype = elt.options[elt.selectedIndex].value;
//convert data to integers
volwassenen = parseInt(volwassenen);
kinderen = parseInt(kinderen);
peuters = parseInt(peuters);
kamertype = parseInt(kamertype);
//calculate total value
var total = volwassenen + kinderen + peuters + kamertype;
//print value to PicExtPrice
document.getElementById("PicExtPrice").value = total;
}
</script>
</head>
Demo

Your problem is a simple syntax error.
At the end of your code, you have
}
}
The first } closes the function, but the second } is causing an error. Try replacing it with a ) to close the ready function.
Also, I noticed that you didn't reference jQuery, so that is also causing an error. In the left, change the text-box that says "No-Library (pure JS)" to a version of jQuery.

You should make more use of jQuery when referencing it (which you forgot to do in your fiddle by the way). What I think you want to achieve is something like this:
FIDDLE
HTML
<form name="formclear" action="" method="post" id="bootstrap-frm">
<label> <span>Volwassenen :</span>
<select class="autowidthselect" name="prijsvolwassenen" id="prijsvolwassenen">
<option value="-50">1</option>
<option selected="selected" value="0">2</option>
<option value="50">3</option>
<option value="100">4</option>
<option value="150">5</option>
<option value="200">6</option>
<option value="250">7</option>
<option value="300">8</option>
</select>
</label>
<label> <span>Kinderen (4-12 jr) :</span>
<select class="autowidthselect" name="prijskinderen" id="prijskinderen">
<option value="-50">0</option>
<option value="-25">1</option>
<option selected="selected" value="0">2</option>
<option value="25">3</option>
<option value="50">4</option>
<option value="75">5</option>
<option value="100">6</option>
<option value="125">7</option>
</select>
</label>
<label> <span>Kinderen (0-3 jr) :</span>
<select class="autowidthselect" name="prijspeuters" id="prijspeuters">
<option selected="selected" value="0">0</option>
<option value="15">1</option>
<option value="30">2</option>
<option value="45">3</option>
<option value="60">4</option>
<option value="75">5</option>
<option value="90">6</option>
<option value="105">7</option>
</select>
</label>
<label> <span> Kamertype :</span>
<select class="autowidthselect" name="prijskamertype" id="prijskamertype">
<option selected="selected" value="selecteer kamertype">Selecteer kamertype</option>
<option value="295">Kraaiennest</option>
<option value="395">Kajuit</option>
<option value="495">Kapiteinshut</option>
</select>
</label>
<label> <span>Subtotaal: </span>
<input id="PicExtPrice" type="text" size="10" />
</label>
</form>
JS
$(document).ready(function () {
$("select").on("change", function () {
CalculatePrice();
});
$("#CalculatePrice").on("click", function () {
CalculatePrice();
});
});
function CalculatePrice()
{
var pv = parseInt($("#prijsvolwassenen").val(), 10);
var pk = parseInt($("#prijskinderen").val(), 10);
var pp = parseInt($("#prijspeuters").val(), 10);
var pkt = parseInt($("#prijskamertype").val(), 10);
if (!isNaN(pkt))
$("#PicExtPrice").val(pv+pk+pp+pkt);
}
EDIT: Updated answer using vanilla JS:
Make your JS like this:
JS
function calculatePrice() {
//Get selected data
var elt = document.getElementById("prijsvolwassenen");
var volwassenen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskinderen");
var kinderen = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijspeuters");
var peuters = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("prijskamertype");
var kamertype = elt.options[elt.selectedIndex].value;
//convert data to integers
volwassenen = parseInt(volwassenen);
kinderen = parseInt(kinderen);
peuters = parseInt(peuters);
kamertype = parseInt(kamertype);
//check if each value is a number and calculate total value
if (!isNaN(volwassenen) && !isNaN(kinderen) && !isNaN(peuters) && !isNaN(kamertype)) {
var total = volwassenen + kinderen + peuters + kamertype;
//print value to PicExtPrice
document.getElementById("PicExtPrice").value = total;
}
}
VANILLA FIDDLE

More DRY code http://jsfiddle.net/B6mPP/6/
$(function(){
var fields = $('#prijsvolwassenen,#prijskinderen,#prijspeuters,#prijskamertype'),
total = $('#PicExtPrice');
function calculateTotal(){
var sum = 0;
fields.each(function(){
var value = parseInt($(this).val());
value == value && (sum += value);
})
total.val(sum);
};
fields.change(calculateTotal);
$('#calculate').click(calculateTotal);
});

demo: https://so.lucafilosofi.com/calculate-total-price-script-not-working/
$(function(){
$('.autowidthselect').on('change', function(){
calculatePrice();
});
$('button').on('click', function(){
calculatePrice();
return false;
});
function calculatePrice() {
var total = 0;
$('.autowidthselect').each(function(){
total += !isNaN(this.value) ? parseInt(this.value) : 0;
});
$("#PicExtPrice").val(total);
}
});
vanila javascript fix
http://jsfiddle.net/B6mPP/10/

Related

javascript change select time when choice is change

i have an choice where the element inside are generate by php (and can change everyday).
i would like to change an other select(time) when my first select change.
My first select is a choice where the value is the time at start and at end.
My second select is a choice wwith the time between start and stop.
when my page is load i must to override the select.
My probleme is for change the value a second time .
//select service
var serviceCheck = document.getElementById("order_openname");
var hoursSelect = document.getElementById("order_ready_at_hours");
var serviceValue = serviceCheck.value;
var serviceValueHourStart = serviceValue.substring(0, 2);
var serviceValueMinuteStart = serviceValue.substring(3, 5);
var serviceValueHourStop = serviceValue.substring(9, 11);
var serviceValueMinuteStop = serviceValue.substring(12, 15);
// change select at start
var select = document.createElement("select");
select.name = "order[ready_at][hours]";
select.classList.add("form-control");
hoursSelect.replaceWith(select, hoursSelect);
hoursSelect.remove();
for (serviceValueHourStart; serviceValueHourStart < serviceValueHourStop; serviceValueHourStart++) {
var addHours = String(serviceValueHourStart);
var option = document.createElement("option");
option.text = addHours;
select.add(option);
}
// change select when service is change
serviceCheck.addEventListener('change', function () {
serviceValue = serviceCheck.value;
serviceValueHourStart = serviceValue.substring(0, 2);
serviceValueMinuteStart = serviceValue.substring(3, 5);
serviceValueHourStop = serviceValue.substring(9, 11);
serviceValueMinuteStop = serviceValue.substring(12, 15);
if (select) {
var selectHours = document.createElement("select");
selectHours.name = "order[ready_at][hours]";
selectHours.classList.add("form-control");
select.replaceWith(selectHours, select);
select.remove();
for (serviceValueHourStart; serviceValueHourStart < serviceValueHourStop; serviceValueHourStart++) {
addHours = String(serviceValueHourStart);
option = document.createElement("option");
option.text = addHours;
selectHours.add(option);
}
}
})
<div class="form-group">
<label class="required" for="order_openname">Service :</label>
<select id="order_openname" name="order[openname]" class="form-control">
<option value="11:01:00|15:01:00">Morning</option>
<option value="18:01:00|22:01:00">Afternoon</option></select></div>
<fieldset class="form-group">
<legend class="col-form-label required">Order for :</legend>
<div id="order_ready_at" class="form-inline"><div class="col-auto">
<label class="required" for="order_ready_at_hours">Hours</label>
<select id="order_ready_at_hours" name="order[ready_at][hours]" class="form-control"><option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
<option value="4">3</option>
<option value="5">4</option>
<option value="6">5</option>
<option value="7">6</option>
<option value="8">7</option>
<option value="9">8</option>
<option value="10">9</option>
<option value="11">10</option>
<option value="12">11</option>
<option value="13">12</option>
<option value="14">13</option>
<option value="15">14</option>
<option value="16">15</option>
<option value="17">16</option>
<option value="18">17</option>
<option value="19">18</option>
<option value="20">19</option>
<option value="21">20</option>
<option value="22">21</option>
<option value="23">22</option>
<option value="24">23</option>
</select>
</div>
If you know a better solution or if you can explain me how can did for change my select more than two time thank you in advance.
Solution
//select service
var serviceCheck = document.getElementById("order_openname");
var hoursSelect = document.getElementById("order_ready_at_hours");
var serviceValue = serviceCheck.value;
var serviceValueHourStart = serviceValue.substring(0, 2);
var serviceValueMinuteStart = serviceValue.substring(3, 5);
var serviceValueHourStop = serviceValue.substring(9, 11);
var serviceValueMinuteStop = serviceValue.substring(12, 15);
var select = document.createElement("select");
select.name = "order[ready_at][hours]";
select.classList.add("form-control");
select.id = "order_ready_at_hours";
hoursSelect.replaceWith(select, hoursSelect);
hoursSelect.remove();
for (serviceValueHourStart; serviceValueHourStart < serviceValueHourStop; serviceValueHourStart++) {
var addHours = String(serviceValueHourStart);
var option = document.createElement("option");
option.text = addHours;
select.add(option);
}
// change select when service is change
serviceCheck.addEventListener('change', function () {
serviceValue = serviceCheck.value;
serviceValueHourStart = serviceValue.substring(0, 2);
serviceValueMinuteStart = serviceValue.substring(3, 5);
serviceValueHourStop = serviceValue.substring(9, 11);
serviceValueMinuteStop = serviceValue.substring(12, 15);
var selectTime = document.getElementById("order_ready_at_hours");
var selectHours = document.createElement("select");
selectHours.name = "order[ready_at][hours]";
selectHours.classList.add("form-control");
selectHours.id = "order_ready_at_hours";
selectTime.replaceWith(selectHours, selectTime);
selectTime.remove();
for (serviceValueHourStart; serviceValueHourStart < serviceValueHourStop; serviceValueHourStart++) {
addHours = String(serviceValueHourStart);
option = document.createElement("option");
option.text = addHours;
selectHours.add(option);
}
})
<div class="form-group">
<label class="required" for="order_openname">Service :</label>
<select id="order_openname" name="order[openname]" class="form-control">
<option value="11:01:00|15:01:00">Morning</option>
<option value="18:01:00|22:01:00">Afternoon</option></select></div>
<fieldset class="form-group">
<legend class="col-form-label required">Order for :</legend>
<div id="order_ready_at" class="form-inline"><div class="col-auto">
<label class="required" for="order_ready_at_hours">Hours</label>
<select id="order_ready_at_hours" name="order[ready_at][hours]" class="form-control"><option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
<option value="4">3</option>
<option value="5">4</option>
<option value="6">5</option>
<option value="7">6</option>
<option value="8">7</option>
<option value="9">8</option>
<option value="10">9</option>
<option value="11">10</option>
<option value="12">11</option>
<option value="13">12</option>
<option value="14">13</option>
<option value="15">14</option>
<option value="16">15</option>
<option value="17">16</option>
<option value="18">17</option>
<option value="19">18</option>
<option value="20">19</option>
<option value="21">20</option>
<option value="22">21</option>
<option value="23">22</option>
<option value="24">23</option>
</select>
</div>

Having trouble with Javascript ordering form not calculating

So I'm getting a null error with my order form when I'm trying to calculate the total using javascript. I believe I have everything done. I get an error on line 13 below that starts with .innerHTML
<script type="text/javascript">
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var price = document.getElementById(strains[i] + priceStr).value;
var quantity = document.getElementById(strains[i] + quantityStr).value;
document.getElementById(strains[i] + subtotalStr)
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
document.getElementById("finaltotal").innerHTML = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
</script>
Here is the HTML that is associated just one example they are all the same with unique id and names.
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Full Example:
https://jsfiddle.net/dg260zxf/
Also if I could just make this work without the subtotal since I don't think it's necessary that would be awesome.
the problem is the array contains many Divs than not in HTML,
the first item 'guptakush_' only exist in html
so if you check if div exists before settings value it will resolve the problem
+
the finaltotal is input not html so put new value with .value not .inerHTML
Working demo:
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var priceInput = document.getElementById(strains[i] + priceStr);
var quantityInput = document.getElementById(strains[i] + quantityStr);
var subTotalDiv = document.getElementById(strains[i] + subtotalStr);
if(subTotalDiv) {
var price = priceInput.value;
var quantity = quantityInput.value;
subTotalDiv
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
}
document.getElementById("finaltotal").value = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Plenty of issues:
You hadn't defined subtotalStr, so that was null
You weren't executing your setup function because you didn't include parentheses
Your <strong> element doesn't seem to be populatable when selecting it by ID (not sure what was up w/that, but changing it to a div worked).
Check this: https://jsfiddle.net/mj1z9bvq/
In my version, I fixed the first two problems. And then for the first <strong> element, I replaced it with a <div> so you could see the output. You'll have to go through and do something similar for the others.

how sum data attribute total price?

I have select boxes, and they have data attribute (data-price). I want to sum selected option "data-price" as "total" . but I have one problem. If I select only value="bmw" or I have not selected anything it gives me NaN$.
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#total').html(sum + '$');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>
This code will fix your problem:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
var price = $(this).data('price');
if(price){
sum += $(this).data('price');
}
});
$('#total').html(sum + '$');
});
If you log the pricevariable into the forEach loop, you can see that it returns an integer and then an undefined. That should be fixed! :)
When you select only one option the selected option of the other does not have a 'data-price' attribute:
<option value="">--</option> <!-- data-price === "undefined" -->
You could set a default of "0" to the initially selected option:
<option value="" data-price="0">--</option>
Example:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#total').html(sum + '$');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="" data-price="0">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="" data-price="0">--</option>
<option value="series-1" data-price="2000">3 series</option>
<option value="series-1" data-price="3000">5 series</option>
</select>
<div id="total"> </div>
When you change one dropdown, let's say Make, $selected will include two elements:
<option value="bmw" data-price="200">bmw</option> and <option value="">--</option>
When you are now calculating the sum, you are adding two values 200 and and empty string as strings. You should try to parse all values to integers with parseInt("string", 10) (Note the 10 parameter which specifies the base to be used, it's good practice to be explicit, see parseInt documentation here).
Also, as other answers here state, you should always try to default to an integer value (in the case of the empty string). So your code could now be like this:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
var optionPrice = parseInt($(this).data('price'), 10) || 0;
sum += optionPrice;
});
$('#total').html((sum) ? (sum + '$') : '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>
You must to parse your data which is seen as a string
$selected.each(function() {
var data = $(this).data('price');
if(data != undefined){
sum += parseFloat(data);
}
});
Please use a fallback value of 0 if the returned value is undefined.
using the line.
sum += $(this).data('price') || 0;
Note: You also need to run this validation function at the beginning to ensure, the result is calculated at the beginning before the change() event.
function validate(){
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price') || 0;
});
$('#total').html(sum === 0 ? '' : sum + '$');
}
validate();
$('#mark, #series').on('change', function() {
validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>

Getting value of drop down list JavaScript

How to make that the all selected options, not the values, but the actual text, would be displayed somewhere?
Html:
<h1>Made your PC:</h1>
<div>
<label>Processeor: </label><select id="processor" name="processor">
<option class="label" value>Select Processor</option>
<!-- Home Ware -->
<option value="P1">Processor 1</option>
<option value="P2">Processor 2</option>
<option value="P3">Processor 3</option>
<option value="P4">Processor 4</option>
</select>
</div>
<p><strong>Only compatible components will show.</strong></p>
<div>
<label>Select motherboard: </label><select id="motherboard" name="motherboard" class="subcat" disabled="disabled">
<option class="label" value>Select Motherboard</option>
<!-- Home Ware -->
<option rel="P1 P2" value="AS1">ASUS RAMPAGE V EXTREME</option>
<option rel="P2 P3" value="AS2">ASUS ATX DDR3 2600 LGA</option>
<option rel="P1 P3 P4" value="GB1">Gigabyte AM3+</option>
<option rel="P2 P4" value="MSI1">MSI ATX DDR3 2600 LGA 1150</option>
</select>
</div>
<div>
<label>Select RAM: </label> <select disabled="disabled" class="subcat" id="RAM" name="RAM">
<option class="label" value>RAM Memory</option>
<option rel="AS1 AS2 GB1" value="KI1">Kingston Value RAM</option>
<option rel="AS1 AS2 MSI1" value="P5KPL">P5KPL-AM SE</option>
<option rel="MSI1 GB1" value="960GM">960GM-VGS3 FX </option>
</select>
</div>
<div>
<label>Select Video Board: </label> <select disabled="disabled" class="subcat" id="video-card" name="video-card">
<option class="label" value>Video Card</option>
<option rel="MSI1 AS2" value="EVGA8400">EVGA GeForce 8400 GS</option>
<option rel="AS1" value="XFXAMD">XFX AMD Radeon HD 5450</option>
<option rel="MSI1 GB1" value="GTX750Ti">EVGA GeForce GTX 750Ti SC</option>
</select>
</div>
Javascript:
$(function(){
var $supcat = $("#processor"),
$cat = $("#motherboard"),
$subcat = $(".subcat");
$supcat.on("change",function(){
var _rel = $(this).val();
$cat.find("option").attr("style","");
$cat.val("");
if(!_rel) return $cat.prop("disabled",true);
$cat.find("[rel~='"+_rel+"']").show();
$cat.prop("disabled",false);
});
$cat.on("change",function(){
var _rel = $(this).val();
$subcat.find("option").attr("style","");
$subcat.val("");
if(!_rel) return $subcat.prop("disabled",true);
$subcat.find("[rel~='"+_rel+"']").show();
$subcat.prop("disabled",false);
});
});
I tried this one code that was posted earlier, but it only display one selection, right after picking, is there any way it could display all the selections and with my random text, like "Your selections"?:
<script>
function myNewFunction(sel)
{
alert(sel.options[sel.selectedIndex].text);
}
</script>
<select id="box1" onChange="myNewFunction(this);" >
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
This should give the actual label text, not the value, for a given select-element.
$(selector).find(":checked").html()
So if you want to show all of them, you could do something like this:
$("#video-card").on("change", function () {
var choices = [];
$("select").each(function() {
choices.push($(this).find(":checked").html());
});
alert("You selected: " + choices.join(', '));
})
And here's a codepen for demo purposes
http://codepen.io/anon/pen/XbjKYQ
function myNewFunction(sel) {
alert($(sel).val());
}
This should actually be working.
If that doesn't work, try to place a window.setTimeout(function() { ... }, 10); around your alert. It's possible that the browser calls the myNewFunction() method before it updates the selection value when the user clicks on one option.
EDIT: If you want the text instead of the value, use
alert($(sel).find("option:selected").text());
You need to loop through each of the selects, not just the first one:
function updateOutput() {
var selects = document.getElementsByTagName('SELECT');
var output = document.getElementById('output');
var arr = [];
for (i=0; i < selects.length; i++) {
arr.push(selects[i].options[selects[i].selectedIndex].text);
}
output.innerHTML = arr.join('; ');
return arr;
}
In this case, I push all the values into an array and then join the array values at the end to create the final string.
I updated a codepen provided earlier: http://codepen.io/anon/pen/WvGxgz

Javascript code hide show price * quantity to show total

I have this problem with my code I cant make it to deliver me the answer I want. I want to select one of the options for the product and then one of the options for price then input the quantity and to have the Sub-Total delivered by the code.
The problem is that since I have different products and each product has 3 different prices I need my code to deliver the right answer.
The code I have right now is only taking the value of the first price of the first product, and I can't seem to make it work, I feel like I almost have the code... please help me :)
<div>Product<br />
<select id="producto1">
<option >Selecciona</option>
<option value="00">---ALARMAS---</option>
<option value="01">EXTREME BLACK</option>
<option value="02">EXTREME COBRA</option>
<option value="03">EXTREME GALACTIC</option>
</select></div>
<table>
<tbody>
<tr class="e01">
<td class="0"> </td>
<td class="01"><label>Price</label><br />
<select id="elias">
<option value="180">180</option>
<option value="200">200</option>
<option value="220">220</option>
</select></td>
<td class="02"><label>Price</label><br />
<select id="elias1">
<option value="50">50</option>
<option value="20">20</option>
<option value="22">22</option>
</select></td>
<td class="03"><label>Price</label><br />
<select id="elias2">
<option value="80">80</option>
<option value="100">100</option>
<option value="120">120</option>
</select></td>
</tr>
</tbody>
</table>
<div>
<label for="CAT_Custom_500436">Quantity</label><br />
<input type="text" maxlength="255" name="CAT_Custom_500436" id="CAT_Custom_500436" /></div>
<div><label for="CAT_Custom_500440">Sub-Total</label><br />
<input type="text" maxlength="255" name="CAT_Custom_500440" id="CAT_Custom_500440" /></div>
<br />
Java___
(function($) {
$("document").ready(function() {
$("td").hide();
$("#producto1").change(function() {
$(".e01 td").hide();
$("td." + $(this).val()).show();
});
});
})(jQuery);
var e = document.getElementById("elias");
var strUser = e.options[e.selectedIndex].value;
var e = document.getElementById("elias1");
var strUser1 = e.options[e.selectedIndex].value;
var e = document.getElementById("elias2");
var strUser2 = e.options[e.selectedIndex].value;
$(function () {
$('input').keyup(function (){
var quantity1 = $("#CAT_Custom_500436").val();
var total1 = quantity1 * strUser;
var total1 = quantity1 * strUser1;
var total1 = quantity1 * strUser2;
$("#CAT_Custom_500440").val(total1);
});
});
You can try something in these lines
$(document).ready(function () {
// Cache the variables
var $elias = $('#elias'),
$elias1 = $('#elias1'),
$elias2 = $('#elias2'),
$product = $('#producto1'),
$error = $('.error'),
$container = $('.container');
$("td").hide();
var productValue;
$product.change(function () {
$(".e01 td").hide();
$("td." + $(this).val()).show();
// Only show the container when the selections are not first 2
if (this.value !== 'Selecciona' && this.value !== '00') {
$error.addClass('hide');
$container.removeClass('hide');
} else {
$error.removeClass('hide');
$container.addClass('hide');
}
productValue = this.value;
}).change();
// Bind the change event for Dropdowns
var $quantity = $('#CAT_Custom_500436'),
$total = $("#CAT_Custom_500440");
$elias.add($elias1).add($elias2).change( findTotal);
$quantity.keyup(findTotal);
function findTotal() {
// Get the value
var quan = $quantity.val();
var pri = $('.'+ productValue).find('select').val();
var tot = pri * quan;
$total.val(tot);
}
});
Check Fiddle

Categories