Having trouble with Javascript ordering form not calculating - javascript

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.

Related

how to calclate time values via 2 select dropdowns in javascript and display results

I am trying to make a booking form that has booking options for hours and am/pm values and then displays the amount of time chosen by the user for a booking duration
something like 2 selects for the hours
and another 2 selects for the am and pm values
so if a user selects a booking form 10 am, to 3.30pm it whould display
booking duration is for 5.30 hours
I have the code below , it does not work correctly when am and pm values are selected , and I think there must be a much better way to write the javascript than the way I have coded it, any help with this would be good, thanks
the javascript
<script type="text/javascript">
//We use this this array when the user selects a booking time from the form
var booking_ampm = new Array();
booking_ampm["am"] = 0;
booking_ampm["pm"] = 12;
//We use this this array when the user selects a booking time from the form
var booking_prices = new Array();
booking_prices["1"] = 1;
booking_prices["130"] = 1.5;
booking_prices["2"] = 2;
booking_prices["230"] = 2.5;
booking_prices["3"] = 3;
booking_prices["330"] = 3.5;
booking_prices["4"] = 4;
booking_prices["430"] = 4.5;
booking_prices["5"] = 5;
booking_prices["530"] = 5.5;
booking_prices["6"] = 6;
booking_prices["630"] = 6.5;
booking_prices["7"] = 7;
booking_prices["730"] = 7.5;
booking_prices["8"] = 8;
booking_prices["830"] = 8.5;
booking_prices["9"] = 9;
booking_prices["930"] = 9.5;
booking_prices["10"] = 10;
booking_prices["1030"] = 10.5;
booking_prices["11"] = 11;
booking_prices["1130"] = 11.5;
booking_prices["12"] = 12;
booking_prices["1230"] = 12.5;
//This function finds the booking start time based on the drop down selection
function getStartTime()
{
var bookingStartTime = 0;
//Get a reference to the form id="bookingform"
var theForm = document.forms["bookingform"];
//Get a reference to the select id="time_from"
var selectedTime = theForm.elements["time_from"];
var selectedAmPm = theForm.elements["time_from_am_pm"];
bookingStartTime = booking_prices[selectedTime.value];
bookingTimeAmPm = booking_ampm[selectedAmPm.value];
bookingStartTime = bookingStartTime + bookingTimeAmPm;
//finally we return bookingStartTime
return bookingStartTime;
}
//This function finds the booking end time based on the drop down selection
function getEndTime()
{
var bookingEndTime = 0;
//Get a reference to the form id="bookingform"
var theForm = document.forms["bookingform"];
//Get a reference to the select id="time_to"
var selectedTime = theForm.elements["time_to"];
var selectedAmPm = theForm.elements["time_to_am_pm"];
bookingEndTime = booking_prices[selectedTime.value];
bookingTimeAmPm = booking_ampm[selectedAmPm.value];
bookingEndTime = bookingEndTime + bookingTimeAmPm;
//finally we return bookingEndTime
return bookingEndTime;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
//var bookingPrice = getStartTime() + getEndTime();
var bookingPrice = getEndTime() - getStartTime();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Booking is for hours = " + bookingPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
</script>
the html form
<form class="form-horizontal" action="#" id="bookingform">
<fieldset class="content-group">
<legend class="text-bold">Booking Request</legend>
<div class="form-group">
<label class="control-label col-lg-2 text-semibold">User:</label>
<div class="col-lg-10">
<div class="form-control-static">This is the username</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 text-semibold">Booking Type:</label>
<div class="col-lg-10">
<select name="booking_type" class="form-control">
<option value="0">Select booking type</option>
<option value="online">Online Booking</option>
<option value="local">Local Booking</option>
<option value="other">Other Booking Request</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 text-semibold">Date:</label>
<div class="col-lg-10">
<input type="text" name="date" class="form-control">
</div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<div class="col-md-6">
<div class="row">
<label class="control-label col-lg-2 text-semibold">From:</label>
<div class="col-lg-5 pr-20">
<div class="form-group">
<select id="time_from" name="time_from" class="form-control" onchange="calculateTotal()">
<option value="1">1</option>
<option value="130">1:30</option>
<option value="2">2</option>
<option value="230">2:30</option>
<option value="3">3</option>
<option value="330">3:30</option>
<option value="4">4</option>
<option value="430">4:30</option>
<option value="5">5</option>
<option value="530">5:30</option>
<option value="6">6</option>
<option value="630">6:30</option>
<option value="7">7</option>
<option value="730">7:30</option>
<option value="8">8</option>
<option value="830">8:30</option>
<option value="9">9</option>
<option value="930">9:30</option>
<option value="10">10</option>
<option value="1030">10:30</option>
<option value="11">11</option>
<option value="1130">11:30</option>
<option value="12">12</option>
<option value="1230">12:30</option>
</select>
</div>
</div>
<div class="col-lg-5 pr-20">
<div class="form-group">
<select id="time_from_am_pm" name="time_from_am_pm" class="form-control" onchange="calculateTotal()">
<option value="pm">pm</option>
<option value="am">am</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<label class="control-label col-lg-2 pl-20 text-semibold">To:</label>
<div class="col-lg-5 pr-20">
<div class="form-group">
<select id="time_to" name="time_to" class="form-control" onchange="calculateTotal()">
<option value="1">1</option>
<option value="130">1:30</option>
<option value="2">2</option>
<option value="230">2:30</option>
<option value="3">3</option>
<option value="330">3:30</option>
<option value="4">4</option>
<option value="430">4:30</option>
<option value="5">5</option>
<option value="530">5:30</option>
<option value="6">6</option>
<option value="630">6:30</option>
<option value="7">7</option>
<option value="730">7:30</option>
<option value="8">8</option>
<option value="830">8:30</option>
<option value="9">9</option>
<option value="930">9:30</option>
<option value="10">10</option>
<option value="1030">10:30</option>
<option value="11">11</option>
<option value="1130">11:30</option>
<option value="12">12</option>
<option value="1230">12:30</option>
</select>
</div>
</div>
<div class="col-lg-5 pr-20">
<div class="form-group">
<select id="time_to_am_pm" name="time_to_am_pm" class="form-control" onchange="calculateTotal()">
<option value="pm">pm</option>
<option value="am">am</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 text-semibold">Duration:</label>
<div class="col-lg-10">
<input type="text" name="duration" class="form-control">
</div>
</div>
</fieldset>
<div id="totalPrice"></div>
<fieldset class="content-group">
<legend class="text-bold">Booking Comments</legend>
<div class="form-group">
<label class="control-label col-lg-2 text-semibold">Comments:</label>
<div class="col-lg-10">
<textarea rows="5" cols="5" name="comments" class="form-control"></textarea>
</div>
</div>
</fieldset>
<div class="text-right">
<button type="submit" class="btn btn-primary">Submit Booking<i class="icon-arrow-right14 position-right"></i></button>
</div>
</form>
You should be able to fix that via a simple change to the option's value.
<select id="time_from_am_pm" name="time_from_am_pm" class="form-control" onchange="calculateTotal()">
<option value="12">pm</option>
<option value="0">am</option>
</select>
<select id="time_to_am_pm" name="time_to_am_pm" class="form-control" onchange="calculateTotal()">
<option value="12">pm</option>
<option value="0">am</option>
</select>
I hope that this little script can do for you and to calculate in real time the values entered using the onchange event!
var Booking = function() {
this.Calculate = function(hours, minutes, isPM) { // function to calculate the time. (Returns: The date object!.)
if (typeof isPM === "undefined") isPM = false; // if ISPM is not defined, then sets default values
if (isPM) hours = hours + 12; // if isPM is true, then add 12 hours
var d = new Date(); // I create a new watch!
d.setTime(0); // Reset the clock
d.setMinutes(minutes); // set minutes!
d.setHours(hours); // set hours!
return d;
}
this.Offset = function(Day, Month, Year) {
var d = new Date(); // I create a new watch!
d.setTime(0); // Reset the clock
d.setDate(Day); // set day
d.setMonth(Month); // set month
d.setFullYear(Year); // set Year
return d;
}
this.dateDefault = function() {
var d = new Date(); // I create a new watch!
d.setTime(0); // Reset the clock
return d;
}
this.Result = function(Start, End, Offset) {
if (typeof Start === "undefined" || Start == false) Start = this.dateDefault(); // if the variable is undefined or false, loads default values
if (typeof End === "undefined" || End == false) End = this.dateDefault();
if (typeof Offset === "undefined" || Offset == false) Offset = this.dateDefault();
var d = new Date(); // I create a new watch!
d.setTime((End.getTime() - Start.getTime()) + Offset.getTime()); // calculates the time with milliseconds and sets the clock
return d;
}
}
// A small example of how to use the function =)
var test = new Booking();
var start = test.Calculate(1, 15, false); // calculate start time
var end = test.Calculate(5, 15, true); // calculate end time
var offset = test.Offset(28, 12, 2016); // calculate the offset
var result = test.Result(start, end, offset); // calculate the result
// GET YOUR DATA!
var minutes = result.getMinutes();
var hours = result.getHours();
var day = result.getDate();
// .. and much more! Look at the documentation of the link to find out more!
A small example of how to use the function =)
var test = new Booking();
var start = test.Calculate(1, 15, false); // calculate start time
var end = test.Calculate(5, 15, true); // calculate end time
var offset = test.Offset(28, 12, 2016); // calculate the offset
var result = test.Result(start, end, offset); // calculate the result
// GET YOUR DATA!
var minutes = result.getMinutes();
var hours = result.getHours();
var day = result.getDate();
// .. and much more! Look at the documentation of the link to find out more!
DOCUMENTATION: http://www.w3schools.com/jsref/jsref_obj_date.asp

Remove specific value in Javascript Array dynamically

I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}   
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}
You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array
If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)

Product Filtering PHP

Hello guys I'm doing a product filtering and I don't know how could I achieve it.
I used Javascript by getting the value of the selected values then alert it but the problem is that how could I display it also how can I remove the categories selected by clicking the x button. Here the sample page. Thank you very much for your help.
Here is my script code:
<script>
jQuery("#filter").val()
jQuery(function(){
jQuery( ".product-line" ).each(function( index ) {
var url = '<?php echo $upload_url; ?>';
var desc_id = jQuery(this).eq(0).find('.prod-desc').attr('id');
if(desc_id){
var file_url = url + desc_id + '/description.html';
jQuery('#'+desc_id).eq(0).load( file_url );
}
});
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
        var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories =[];
if(brand)
{
categories.push(brand);
}
if(screen_size)
{
categories.push(screen_size);
}
if(cpu)
{
categories.push(cpu);
}
if(memory)
{
categories.push(memory);
}
if(price)
{
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
alert(categories2);
var categories3="";
for(var i = 0; i < length; i++){
categories3 += "<div class='filter_style'>"+categories[i]+"<span style='margin-left:15px;color:gray;'>x</span></div>";
jQuery("#filter").html(categories3);
}
      });
});
</script>
 My HTML Code:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
</div>
There is possibilities, I will UPDATE the answer if it wasn't correct.
But first can you help what will you get after you run this code?
jQuery("#brand,#screen_size").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
console.log(brand);
console.log(screen_size);
});

Other radio buttons not clickable after using Javascript function to select certain Radio based on if statement

I am working on a car service reservation system and there are three different vehicle options. I am trying to code it to where if there are a certain number of passengers listed, the vehicle automatically switches to something that accommodates more people and disables the first vehicle.
I have accomplished this but there are problems. I'm using arrays and functions to define the amount of passengers. I am then using a variable that adds the values these functions spit out to create a total number of passengers. Then I have set up an if statement to say if the value is greater than four, change to this radio input and disable the first one.
The problem occurs when this happens I am no longer able to select the third vehicle option and I don't know why.
I also attempted to set the total passenger value to where if it is less than five, the first vehicle is automatically selected. This did not work either.
Ultimately I would like it to act in such a way that if over 14 passengers are selected, the user receives an error (this is working fine). If less than 5 passengers are selected, the first vehicle is selected. If over 4 passengers are selected, the second vehicle is selected and the third is still an option. If more than 8 passengers are selected, both the first and third vehicle are disabled.
Hopefully my code is not overly ill formatted. I am fairly new to Javascript and have been piecing tutorials together. Here is a jsfiddle of the part of the form that is not working.
Here is the Javascript code:
var adults_teenagers2 = new Array();
adults_teenagers2["1"] = 1;
adults_teenagers2["2"] = 2;
adults_teenagers2["3"] = 3;
adults_teenagers2["4"] = 4;
adults_teenagers2["5"] = 5;
adults_teenagers2["6"] = 6;
adults_teenagers2["7"] = 7;
adults_teenagers2["8"] = 8;
adults_teenagers2["9"] = 9;
adults_teenagers2["10"] = 10;
adults_teenagers2["11"] = 11;
adults_teenagers2["12"] = 12;
adults_teenagers2["13"] = 13;
adults_teenagers2["14"] = 14;
function AmountAdultsTeenagers() {
var AdultsTeenagersNumberAmount = 0;
var theForm = document.forms["resForm"];
var AdultsTeenagersNumber = theForm.elements["adults_teenagers"];
AdultsTeenagersNumberAmount = adults_teenagers2[AdultsTeenagersNumber.value];
return AdultsTeenagersNumberAmount;
}
var children2 = new Array();
children2["0"] = 0;
children2["1"] = 1;
children2["2"] = 2;
children2["3"] = 3;
children2["4"] = 4;
children2["5"] = 5;
children2["6"] = 6;
children2["7"] = 7;
children2["8"] = 8;
function Amountchildren() {
var childrenNumberAmount = 0;
var theForm = document.forms["resForm"];
var childrenNumber = theForm.elements["children"];
childrenNumberAmount = children2[childrenNumber.value];
return childrenNumberAmount;
}
var infants2 = new Array();
infants2["0"] = 0;
infants2["1"] = 1;
infants2["2"] = 2;
infants2["3"] = 3;
infants2["4"] = 4;
infants2["5"] = 5;
infants2["6"] = 6;
infants2["7"] = 7;
infants2["8"] = 8;
function Amountinfants() {
var infantsNumberAmount = 0;
var theForm = document.forms["resForm"];
var infantsNumber = theForm.elements["infants"];
infantsNumberAmount = infants2[infantsNumber.value];
return infantsNumberAmount;
}
function calculateTotal() {
var over = AmountAdultsTeenagers() + Amountchildren() + Amountinfants();
if(over>'14')
{
alert('Sorry, no vehicle can accomodate more than 14 passengers.');
document.getElementById("firstPageSubmit").disabled = true;
}
else {
document.getElementById("firstPageSubmit").disabled = false;
}
if(over<'5') {
document.getElementById("towncar").checked = true;
}
if(over>'4')
{
document.getElementById("towncar").disabled = true;
document.getElementById("stretch_limousine").disabled = false;
document.getElementById("passenger_van").checked = true;
}
else {document.getElementById("towncar").disabled = false;
}
}
and the HTML:
<form method="post" class="res_form" id="resForm" name="res_form" onSubmit="return quoteCheck();">
<ul>
<li id="steps">Step 1 of 3 - Select Type of Service/Get Quote</li>
<li class="form_notice"><span>Reservations must be at least 48 hrs prior for towncars and 72 hrs for any other vehicle.</span></li>
<li><fieldset class="res_form_fs" id="passengers">
<legend>Passengers:</legend>
<label for="adults_teenagers" class="selectLabel">Adults/Teenagers:
<select name="adults_teenagers" id="adults_teenagers" onchange="calculateTotal()">
<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>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select></label>
<label for="children" class="selectLabel">Children:
<select name="children" id="children" onchange="calculateTotal()">
<option value="0">None</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>
</select></label>
<label for="infants" class="selectLabel">Infants:
<select name="infants" id="infants" onchange="calculateTotal()">
<option value="0">None</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>
</select></label>
</fieldset>
</li>
<li>
<fieldset class="res_form_fs">
<legend>Select Vehicle:</legend>
<p class="radioT"><input type="radio" value="Towncar" onclick="calculateTotal()" name="vehicle" id="towncar" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="towncar">Towncar</label></span></p><br />
<p class="radioT"><input type="radio" value="Passenger Van" onclick="calculateTotal()" name="vehicle" id="passenger_van" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="passenger_van">Passenger Van</label></span></p><br />
<p class="radioT"><input type="radio" value="Stretch Limousine" onclick="calculateTotal()" name="vehicle" id="stretch_limousine" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="stretch_limousine">Stretch Limousine</label></span></p>
</fieldset>
</li>
<li><input name="submit" type="submit" id="firstPageSubmit" class="ressubmitButton" value="Continue to Make Reservation" /></li>
</ul>
</form>
Here i change name all select option as same and now it's work. Please see in below JSFiddle:
<select name="adults_teenagers">
http://jsfiddle.net/ketan156/cthbg27h/8/
edit:
change in if condition: following is new JSFiddle:
http://jsfiddle.net/ketan156/cthbg27h/10/
is is ok? as per my understanding you like to get it.
As You need i edited JSFiddle:
http://jsfiddle.net/ketan156/cthbg27h/11/

Calculate total price script not working

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/

Categories