I am trying to add two functions calculate1() and calculate2(). Both functions are taking values from function populate(). Is the code wrong? Once I enter an amount on both functions, the result is total amount undefined.
<form>
Car:
<select id="slct1" name="slct1" onchange="populate('slct1','slct2')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Car:
<select id="slct2" name="slct2">
</select>
<label> Amount <input style="width:10%" type="number" name="amount1" id="amount1" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer1" id="answer1"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
</form>
<!--Starts 2 selection-->
<form>
Food:
<select id="slct1a" name="slct1a" onchange="populate('slct1a','slct2a')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Food:
<select id="slct2a" name="slct2a">
</select>
<label> Amount <input style="width:10%" type="number" name="amount2" id="amount2" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer2" id="answer2"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
<p id="ansCAL"></p>
</form>
<input type="reset" onclick="resetFunctions()" value="Reset">
</script>
var t = total1 + total2;
function result() {
document.getElementById('ansCAL').value = calculate1() + calculate2();
}
function populate(select1, select2)
{
var Brand1 = document.getElementById(select1);
var Brand2 = document.getElementById(select2);
Brand2.innerHTML = "";
if(Brand1.value == "Fiat")
{
var optionArray = ["|","4000|Uno","5000|Ritmo","6000|Panda"];
}
else if(Brand1.value == "Dodge")
{
var optionArray = ["|","4000|Avanger","5000|Challengere","6000|Charger"];
}
else if(Brand1.value == "Ford")
{
var optionArray = ["|","7000|Mustang","8000|Shelby","focus|Focus"];
}
for(var option in optionArray)//the options within the optionArray
{
var pair = optionArray[option].split("|");//in tha variable pair is stored both value and label
var newOption = document.createElement("option");// option in the bracket is used to create new options or you can insert divs paragraph etc
newOption.value = pair[0];//pair 0 gives the value
newOption.innerHTML = pair[1];//pair 1 gives the label
Brand2.options.add(newOption);
}
}
function calculate1() {
Brand1 = document.getElementById('slct1').value;
Brand2 = document.getElementById('slct2').value;
multi=document.getElementById('amount1').value;
total1=parseInt((Brand2)*multi/100);
document.getElementById('answer1').value=total1;
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function calculate2() {
Brand1 = document.getElementById('slct1a').value;
Brand2 = document.getElementById('slct2a').value;
multi=document.getElementById('amount2').value;/*to change accordingly amount1*/
total2=parseInt(((Brand2)*multi)/100);
document.getElementById('answer2').value=total2;/*to change accordingly amount1*/
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function resetFunctions() {
//using the array forEach method on the form
Array.prototype.forEach.call(document.forms,function(el,idx,array){
//the method parameters are element, index and the array
// we loop through all the forms and invoking reset()
el.reset();
});
result();
}
function rstFunction()
{
document.getElementById("ansCAL").innerHTML = "<br>Total amount" + result().value;
}
</script>
The answer was to increase the total in every calculate function. Example (total + total1). Removed the variable t and declared the totals in the printout section.
Related
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.
However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).
I think change method can be used in the same manner.
#Edit:
Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with -566,2202888.
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
<input type="text" id="total" value="0" />
You can loop over all the <select> boxes and text inputs with:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
}
else if (this.id == "binayasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And if you change the checkboxes to use value instead of price, you can do them all in one loop:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
else if (this.id == "binyasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And call the function when any of the inputs are changed:
$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.
Finally, sum the value to the total input. Like this:
let container;
let inputs;
let total;
function calcAndShowTotal() {
let sum = 55435.04798; // it is constant value which must be the beginning value.
let value;
inputs.each(function() {
if ($(this).is('input:checkbox:checked')) {
// If is a checkbox
value = parseFloat($(this).attr('price')) || 0;
sum += value;
} else if ($(this).is('input:text:not(#total)')) {
// If is a text wait until you move to another element
let factor = 1;
if (this.id == 'm2') {
factor = 3134.204499;
} else if (this.id == 'binayasi') {
factor = -566.2202888;
}
value = parseFloat($(this).val()) * factor || 0;
sum += value;
} else if ($(this).is('select')) {
// If is a option from the select element
value = parseFloat($('option:selected', this).val()) || 0;
sum += value;
}
});
total.val(sum);
}
function initHandlers() {
inputs.on('keydown', function(e) {
let focusable, next;
if (e.keyCode == 13) {
focusable = inputs.filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
});
inputs.change(calcAndShowTotal);
calcAndShowTotal();
}
$(function() {
console.log('ready!');
total = $('#total');
container = $('#housepriceguesslist');
inputs = container.find('input:checkbox, input:text, select');
initHandlers();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
Total: <input type="text" id="total" value="0" />
<br/>
<br/>
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" />
Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
Note:
Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when you press tab. Also, I moved the total to the top so you can see the results in the preview.
Update:
I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.
Similar to Barmar's, I added all elements to the .each() loop but also added the .change() handler to all elements:
var context = $('#housepriceguesslist');
var elems = $('input:checkbox, input:text, select', context);
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
elems.each(function() {
if ( $(this).is('input:checkbox:checked') ) {
total += parseFloat($(this).attr('price')) || 0;
} else if ( $(this).is('#m2') ) {
total += parseFloat($(this).val()) * 3134.204499 || 0;
} else if ( $(this).is('#binayasi') ) {
total += parseFloat($(this).val()) * -566.2202888 || 0;
} else if ( $(this).is('select') ) {
total += parseFloat($('option:selected',this).val()) || 0;
}
});
$('#total').val(total);
}
elems.change(calcAndShowTotal); // handlers
calcAndShowTotal(); // first run
See example here: https://jsfiddle.net/qgvsern4/1/
I'm a little confused about why my code doesn't work. I'm very new and am extremely interested to know where I went wrong!
I want to times whichever option I choose by var z but can't get it to work.
This is my code so far:
<td><select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select></td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
<script>
function myFunction() {
var y = document.getElementById("VAS").value;
var z = document.getElementById("number").value;
var a = document.getElementById("VGS").value;
var c = document.getElementById("VAF").value;
var d = document.getElementById("VTS").value;
if (value == VGS) {
var x = a * z;
document.getElementById("value").innerHTML = x;
}
else if (value == VAS) {
var x = y * z;
document.getElementById("value").innerHTML = x;
}
}
</script>
You need to compare the value of the select, not the values of the options. Here's how I fixed your JavaScript code:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
Fully working demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
EDIT:
To do this automatically, use oninput in the number field like so:
<input type="number" id="number" name="number" oninput="myFunction()" />
Demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number" oninput="myFunction()">
</td>
<td>
<br/>
<br/>
<p id="value"></p>
Your values are numbers, so value will never contain VAS. Furthermore, strings need to be surrounded by quotes, so your if-statement will look like this:
if(a == "VAS")
But the value contains numbers, so it should actually be:
if(a == "40")
Note: the values are all strings unless you cast them.
I'm new to javascript and am keen on learning.
I currently have a form that allows the user to select their food, enter their quantity and calculates the price.
My function is able to dynamically calculate the price whenever i change the food item selected. However, if i choose re-enter another quantity, the price will not update dynamically. I'm trying make it so that the price will dyanmically update whenever i change either the food dropdown or the quantity value. Appreciate any kind help.
Thank you.
Attached is my code.
function getSelectValue() {
var selectedValue1 = document.getElementById("dropdownList").value;
if (selectedValue1 === 'Carbonara') {
var currentPrice1 = 4.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
} else {
var currentPrice1 = 3.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
}
var selectedValue2 = document.getElementById("dropdownList2").value;
if (selectedValue2 === 'Carbonara') {
document.getElementById("price_2").value = "4.50";
var currentPrice2 = 4.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "$" + currentPrice1;
} else {
var currentPrice2 = 3.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "3.50";
}
}
Select Food:
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="Prawn Aglio Olio">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_1">
<br>
Price per unit:
<input type="text" id="price_1" value="" disabled>
<br>
<br>
<!-- Second Selection -->
Select Food:
<select id="dropdownList2" name="dropdownList2" onchange="getSelectValue();">
<option value="">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_2">
<br>
Price per unit:
<input type="text" id="price_2" value="" disabled>
<br>
<input type ="button" value="Submit">
<a href="vendor.jsp">
<input type="button" value="Back">
</a>
</form>
Try to write the same event (getSelectedValue()) in the input of quantity
Try to initialize all the variables at the beginning so that everything is cleaner
Check that the input element.value "Quanity" exists, if so, fill in the field of 'price'
Test this
function getSelectValue() {
var dropdownList = document.getElementById("dropdownList");
var price_1 = document.getElementById("price_1")
var amount_1 = document.getElementById("amount_1");
var dropdownList2 = document.getElementById("dropdownList2");
var price_2 = document.getElementById("price_2");
var amount_2 = document.getElementById("amount_2");
var currentPrice1 = "$" + 0;
var currentPrice2 = "$" + 0;
if (amount_1.value) {
if (dropdownList.value === 'Carbonara') {
currentPrice1 = 4.50 * parseFloat(amount_1.value);
} else {
currentPrice1 = 3.50 * parseFloat(amount_1.value);
}
price_1.value = "$" + currentPrice1;
}
if (amount_2.value) {
if (dropdownList2.value === 'Carbonara') {
currentPrice2 = 4.50 * parseFloat(amount_2.value);
} else {
currentPrice2 = 3.50 * parseFloat(amount_2.value);
}
price_2.value = "$" + currentPrice2;
}
}
Select Food:
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="Prawn Aglio Olio">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="number" id="amount_1" onchange="getSelectValue();">
<br>
Price per unit:
<input type="text" id="price_1" value="" disabled>
<br>
<br>
<!-- Second Selection -->
Select Food:
<select id="dropdownList2" name="dropdownList2" onchange="getSelectValue();">
<option value="">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="number" id="amount_2" onchange="getSelectValue();">
<br>
Price per unit:
<input type="text" id="price_2" value="" disabled>
<br>
<input type ="button" value="Submit">
<a href="vendor.jsp">
<input type="button" value="Back">
</a>
</form>
Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<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>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}
I have a pizza ordering form that contains checkboxes for toppings. Each new Pizza is an object that is placed into an array. One of the variables inside the pizza object is toppings. I would like the toppingsvariable to contain an array of all the checkboxes name attribute. How do I do that?
I have made an attempt, but it doesn't seem to work:
HTML:
<fieldset>
<form class="pure-form">
<legend>
<center><label><b>Name: </b></label>
<select class="nameSelection" name="nameSelectionPizza">
<option value="0">Please Select:</option>
</select></center>
</legend>
<br>
<label><b>Pizza Type: </b></label>
<select class="pizza" name="firstMenu" disabled>
<option data-price="0">Please Select:</option>
<option name="margarita">Margarita</option>
<option name="deep-pan">Deep Pan</option>
<option name="stuffed-crust">Stuffed Crust</option>
</select>
<span style="float:right">
<label><b>Pizza Size: </b></label>
<select class="pizzaSize" disabled>
<option data-price="0">Please Select:</option>
<option name="e-small" data-price="4.99">Extra Small - £4.99</option>
<option name="small" data-price="5.99">Small - £5.99</option>
<option name="medium" data-price="6.99">Medium - £6.99</option>
<option name="large" data-price="8.99">Large - £8.99</option>
<option name="e-large" data-price="9.99">Extra Large - £9.99</option>
<option name="f-size" data-price="10.99">Family Size - £10.99</option>
</select>
</span>
</form>
</fieldset>
<fieldset style = "border-top:0px">
<form class="pure-form">
<legend><b>Toppings (99p Each): </b></legend>
<input type="checkbox" class="toppings" name="onions" disabled>Onions</input>
<input type="checkbox" class="toppings" name="mushrooms" disabled>Mushrooms</input>
<input type="checkbox" class="toppings" name="peppers" disabled>Peppers</input>
<input type="checkbox" class="toppings" name="olives" disabled>Olives</input>
<input type="checkbox" class="toppings" name="garlic" disabled> Garlic</input>
<input type="checkbox" class="toppings" name="peperoni" disabled>Peperoni</input>
<input type="checkbox" class="toppings" name="cheese" disabled>Pesto</input>
</form>
</fieldset>
JS:
var pizzaArray = new Array();
function pizza(number, pizzaCost, toppingCost, name, pizzaType, pizzaSize, toppings) {
this.pizzaNumber = number;
this.pizzaCost = pizzaCost;
this.toppingCost = toppingCost;
this.name = name;
this.type = pizzaType;
this.size = pizzaSize;
this.toppings = toppings;
}
var pizzaCounter = 1;
pizzaArray.push(new pizza(pizzaCounter, 0.00, 0.00, "", "", "", ""));
$(document).on("change","input[type='checkbox']", function() {
var topArray = $(":checkbox:checked").next('name').map(function(){
return $(this).attr('name');
}).get();
var checked = $(this).parent().find(":checkbox:checked").length;
var toppingCost = (0.99 * checked);
var form = $(this).closest('div').attr("id");
var formID = form.replace( /^\D+/g, '');
for(var i = 0; i < pizzaArray.length; i++) {
if (pizzaArray[i].pizzaNumber == formID) {
pizzaArray[i].toppingCost = toppingCost;
pizzaArray[i].toppings = topArray;
alert((pizzaArray[i].toppings).toString());
calculateCost();
}
}
});
The error is in your use of next('name'). Remove that and your code should work fine:
var topArray = $(".toppings:checked").map(function(){
return this.name;
}).get();
Note that I changed the selector to use the class of the checkboxes to save any issues if you add further checkboxes to the page in future. I also used the name property directly from the DOMElement to save creating a needless jQuery object.