Doing Calculations with multiple options in Javascript - javascript
I'm quite new to Javascript and have started to do simple calculations, but have run into a barrier with <select>.
I want the code to get what the user has selected in the drop-down menu and multiply the number in the "How many nights?" box. The answer will be displayed in the textbox below. The options in the select menu all have prices tied to them.
< script language = "javascript" >
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val1 = parseInt(document.getElementById("House").value);
var House1 = 100;
var House2 = 175;
var House3 = 150;
var House4 = 135;
var House5 = 150;
var House6 = 120;
var House7 = 180;
var House8 = 120;
var House9 = 80;
var House10 = 105;
var ansD = document.getElementById("answer");
ansD.value = House * Nights;
}
} < /script>
<html>
<head>
<title>Calculate cost</title>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="javascript:addNumbers()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>
With setting the value for the houses inside the select dropdown, you help yourself quite a lot. You can see that the javascript part is greatly reduced, and that it is actually quite simple to sum the values together
Also, it is important that your button is not of type submit, as it would then submit your script, and well, you don't see the result of your calculate function then ;)
function calculate() {
var houseEl = document.getElementById('houseType'),
nightEl = document.getElementById('nightsCount'),
resultEl = document.getElementById('result');
if (houseEl.selectedIndex < 0 || parseInt(nightEl.value) < 0) {
resultEl.innerHTML = 'n/a';
return;
}
resultEl.innerHTML = parseInt(houseEl.options[houseEl.selectedIndex].value) * parseInt(nightEl.value);
}
window.addEventListener('load', function() {
document.getElementById('btnCalculate').addEventListener('click', calculate);
});
<select id="houseType">
<option value="0">None</option>
<option value="100">House 1</option>
<option value="150">House 2</option>
</select>
<input type="number" min="1" value="1" id="nightsCount" />
<button type="button" id="btnCalculate">Calculate</button>
<div>
The total amount for your stay would be <span id="result"></span> €
</div>
I suggest you to use an Object that keeps "key"-"value" pairs.
a is an Object, it contains keys such as House1, House2 and prices as values.
a[val2] will give you a price for staying one night in the hotel.
if None value (or other not available in the Map value) comes from the form,
isNaN() check will give true and No price message will be printed out.
<html>
<head>
<title>Calculate cost</title>
<script language = "javascript">
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val2 = document.getElementById("House").value;
var a={};
var prices = [ 100, 175, 150, 135, 150, 120, 180, 120, 80, 105 ];
for (var i = 1; i < 11; i++)
{
a["House"+i] = prices[i];
}
var ansD = document.getElementById("answer");
if (isNaN(a[val2]))
ansD.value="No price!";
else
ansD.value = val1 * a[val2];
}
</script>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="calculate()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>
Related
Comparing select input values of multiple select inputs to check if a value has been selected
I'm trying to create something like a day/time preference listing. Where preference one is the first day/time set and the second preference is the second day/time set. A minimum of two pairs will be used but more can be added as well. The goal is to be able to select multiple day/time preferences but if someone selects two of the same day then they can only select only one time preference. So if I select Wednesday at 1 for the first preference, then the second can only select Wednesday at 2 or 3. I'm kind of looking for 2 things here. I would prefer to try this using pure javascript. First, here's the code I've come up with so far to try and accomplish the goal I'm looking to do. I want to disable the second preference time value or even clear the input but currently what I've tried doesn't seem to do either. Second, if someone knows a cleaner more unobtrusive way to implement what I'm trying to do as well I'm up for ideas on how to get that done. function getDays(){ var days1 = document.getElementById('pref1-day'), days1_value = days1.options[days1.selectedIndex].value; var days2 = document.getElementById('pref2-day'), days2_value = days2.options[days2.selectedIndex].value; if (days1_value === days2_value) CheckDrodowns(); } function CheckDrodowns(){ var times = document.querySelectorAll('select.times-dropdown'); for (i = 0; i < times.length; i++) { for (j = 0; j < times.length; j++) { if (times[i].id != times[j].id) { if (times[i].options[times[i].selectedIndex].value === times[j].options[times[j].selectedIndex].value) { alert(times[i].options[times[i].selectedIndex].value); //times[i].selected = false; //times[j].options[times[j].selectedIndex].value = ""; return false; } } } } return false; } <div> <SELECT id="pref1-day" class="day-dropdown" style="width:150px"> <option value=""></option> <option value="WED">WEDNESDAY</option> <option value="THU">THURSDAY</option> <option value="FRI">FRIDAY</option> <option value="SAT">SATURDAY</option> </SELECT> <SELECT id="pref1-times" class="times-dropdown" style="width:150px" onChange="getDays()"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </SELECT> </div> <div> <SELECT id="pref2-day" class="day-dropdown" style="width:150px"> <option value=""></option> <option value="WED">WEDNESDAY</option> <option value="THU">THURSDAY</option> <option value="FRI">FRIDAY</option> <option value="SAT">SATURDAY</option> </SELECT> <SELECT id="pref2-times" class="times-dropdown" style="width:150px" onChange="getDays()"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </SELECT> </div> Here is a jsbin link to view the html and javascript code.
I would suggest using checkboxes for an improved user experience: HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div> Wednesday <input name="date" type="checkbox" value="Wednesday at 1pm">1pm</input> <input name="date" type="checkbox" value="Wednesday at 2pm">2pm</input> <input name="date" type="checkbox" value="Wednesday at 3pm">3pm</input> </div> <div> Thursday <input name="date" type="checkbox" value="Thursday at 1pm">1pm</input> <input name="date" type="checkbox" value="Thursday at 2pm">2pm</input> <input name="date" type="checkbox" value="Thursday at 3pm">3pm</input> </div> <div> Friday <input name="date" type="checkbox" value="Friday at 1pm">1pm</input> <input name="date" type="checkbox" value="Friday at 2pm">2pm</input> <input name="date" type="checkbox" value="Friday at 3pm">3pm</input> </div> <div> Saturday <input name="date" type="checkbox" value="Saturday at 1pm">1pm</input> <input name="date" type="checkbox" value="Saturday at 2pm">2pm</input> <input name="date" type="checkbox" value="Saturday at 3pm">3pm</input> </div> <button onClick="getDays();">Get Days</button> </body> </html> JS function getDays() { var elements = document.getElementsByName("date"); var dates = []; for (var i=0; i<elements.length; i++) { if (elements[i].checked) { dates.push(elements[i].value); } } var selectedDates = dates.length > 0 ? dates.join(", ") : "No Dates Selected"; alert(selectedDates); } JS Bin
Try removing the time option by adding a listener when the day is selected as this : <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div> <SELECT id="pref1-day" class="day-dropdown" style="width:150px" onChange="checkDays()"> <option value=""></option> <option value="WED">WEDNESDAY</option> <option value="THU">THURSDAY</option> <option value="FRI">FRIDAY</option> <option value="SAT">SATURDAY</option> </SELECT> <SELECT id="pref1-times" class="times-dropdown" style="width:150px" onChange="getDays()"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </SELECT> </div> <div> <SELECT id="pref2-day" class="day-dropdown" style="width:150px" onChange="checkDays()"> <option value=""></option> <option value="WED">WEDNESDAY</option> <option value="THU">THURSDAY</option> <option value="FRI">FRIDAY</option> <option value="SAT">SATURDAY</option> </SELECT> <SELECT id="pref2-times" class="times-dropdown" style="width:150px" onChange="getDays()"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </SELECT> </div> </body> </html> JS function getDays(){ var days1 = document.getElementById('pref1-day'), days1_value = days1.options[days1.selectedIndex].value; var days2 = document.getElementById('pref2-day'), days2_value = days2.options[days2.selectedIndex].value; if (days1_value === days2_value) CheckDrodowns(); } function CheckDrodowns(){ var times = document.querySelectorAll('select.times-dropdown'); for (i = 0; i < times.length; i++) { for (j = 0; j < times.length; j++) { if (times[i].id != times[j].id) { if (times[i].options[times[i].selectedIndex].value === times[j].options[times[j].selectedIndex].value) { alert(times[i].options[times[i].selectedIndex].value); return false; } } } } return false; } function checkDays(){ var days1 = document.getElementById('pref1-day'), days1_value = days1.options[days1.selectedIndex].value; var days2 = document.getElementById('pref2-day'), days2_value = days2.options[days2.selectedIndex].value; if (days1_value === days2_value){ var times1 = document.getElementById('pref1-times'), times2 = document.getElementById('pref2-times'); times2.remove(times1.selectedIndex); } }
finding some based on checkbox and select
i am trying to find SUM of some number based on check box and select option . here is my code <div class="container"> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <label> <input type="checkbox" value="10">10 </label> </div> <input id="total" placeholder="total" /> And my script is function updateTotal(){ var total = 0; $(".container input[type='checkbox']").each(function(){ if($(this).is(":checked")){ var multiplier = Number($(this).parent().prev().val()); var checkboxAmount = Number($(this).val()); total += multiplier * checkboxAmount; } }); $("#total").val(total); } $("select, input[type='checkbox']").on("change", updateTotal); The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output i wanted my HTML code like this , then script should be work fine for this <div class="container"> <label> <input type="checkbox" value="10">10 </label> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </div> <input id="total" placeholder="total" /> any help , code coppied from here
Try this one- function updateTotal() { var total = 0; $(".container").each(function () { var checkbox = $(this).find("input[type='checkbox']"); var select = $(this).find("select"); if (checkbox.is(":checked")) { total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val()); } }); }
Javascript dynamic select, using arrays
I have the following code from a very old website. It's from the back end of a system which is used to sell activity holidays, and it only works in IE when Compatibility Mode is engaged. (Hence the meta tag on line 3). <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=6" /> </head> <body bgcolor="#ffffff" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <SCRIPT LANGUAGE="JavaScript"> <!-- Begin function BuildActivityTypeSubTypeDropDown(ActivityTypeId) { var ActivitySubTypeId = 0 var arrActivityTypeId = new Array(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,42,45,46,47,48); var arrActivityTypeName = new Array('Adventure','Sport','Culture','Personal Development','Fitness','Wellbeing','Ski','Cycling','Surfing','Tennis','Fishing','Golf','Walking','Languages','Music','Poker','Bridge','Football','Photography','Cooking','Painting','Airborne','Wine','Cricket','Scrabble','Chess','Mountains','Diving','Kayaking','Windsurfing','Sailing','Riding','Singing','Farming','Creative Writing','Croquet','Drama','Bowls','Motorcycle','Wildlife','Incentive','Spice','Comedy','Boot Camp'); var arrActivitySubTypeId = new Array(190,16,77,12,32,30,99,104,14,112,18,28,34,98,89,97,15,17,170,78,35,74,196,13,109,6,108,68,21,207,95,37,11,110,191,111,90,40,63,43,85,59,65,69,120,169,200,189,202,173,172,216,175,178,136,199,198,176,171,195,197,179,192,168,194,177,205,180,100,181,103,101,162,102,114,119,115,118,116,117,121,122,124,123,186,125,187,126,152,153,131,127,128,130,129,135,133,201,183,132,134,137,138,140,182,139,141,142,144,164,145,143,146,147,148,149,150,151,154,155,156,209,157,213,208,214,211,212,210,158,184,159,160,167,161,163,165,166,203,204,215,193); var arrActivitySubTypeName = new Array('Canyoning','Multi-Activity','Golf','Archaeology','Cooking','Sightseeing','Wine','Outdoor Survival skills','Public Speaking','Aerobics','Bachata','Belrobics','Bollywood Fitness','Booiaka','Boot Camp','Boxfit','Drums Alive','Fitness','Ginastica Natural','Insanity','Kettlebell Workout','Masala Bhangra','Parkour','Personal Training','Pilates','Retreat','Running','Spa','Step Aerobics','Weight Loss','Yoga','Zumba','Nutrition','Pilates','Spa','Weight-Loss','Yoga','Alpine and Downhill','Cross-Country','Snowboarding','Cycle Touring','Mountain Biking','Road Cycling','Surfing','Tennis','Big Game','Carp','Fly','Salmon','Trout','Golf','Hiking','Rambling','Walking','French','German','Italian','Spanish','Classical Concerts','Groups - live concerts','Learn to play','stud','Texas Hold \'em','Bridge','Football','Photography','Baking','Breadmaking','Cooking','Painting','Ballooning','Gliding','Hang-Gliding','Light Aircraft','Para-Gliding','Wine','Cricket','Scrabble','Chess','Climbing and mountaineering','Hiking','Diving','Kayaking','Windsurfing','Bareboat Charter','Big Boat','Cabin Charter','Dinghy','Expedition Adventure Sailing','Flotilla Sailing Holidays','RYA Training Holidays','Skippered Charter','Horseriding','Choral','Urban Farming','Writing','Croquet','Acting and Drama','Bowls','Track days','Birdwatching','Various','Various','Carry on Comedy','Boot Camp'); var arrActivitySubTypeActivityTypeId = new Array(2,2,3,4,4,4,4,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,8,8,8,9,9,9,10,11,12,12,12,12,12,13,14,14,14,15,15,15,15,16,16,16,17,17,18,19,20,21,21,21,22,23,23,23,23,23,24,25,26,27,28,28,29,30,31,32,32,32,32,32,32,32,32,33,35,36,37,38,39,40,41,42,45,46,47,48); var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') var ActivitySubTypeDropDownOption ActivitySubTypeDropDown.options.length = 0; ActivitySubTypeDropDownOption = document.createElement("OPTION"); ActivitySubTypeDropDownOption.value = ''; ActivitySubTypeDropDownOption.text = ''; ActivitySubTypeDropDown.add(ActivitySubTypeDropDownOption); for(var i = 0; i < arrActivitySubTypeId.length; ++i) { if (arrActivitySubTypeActivityTypeId[i] == ActivityTypeId) { ActivitySubTypeDropDownOption = document.createElement("OPTION"); ActivitySubTypeDropDownOption.value = arrActivitySubTypeId[i]; ActivitySubTypeDropDownOption.text = arrActivitySubTypeName[i]; ActivitySubTypeDropDown.add(ActivitySubTypeDropDownOption); if (arrActivitySubTypeId[i] == ActivitySubTypeId) { ActivitySubTypeDropDownOption.selected = true; } } } } // End --> </script> <center> <form name="frmBookings"> Activity Category<br> <select id="ActivityTypeDropDown" name="ActivityTypeId" style="width: 100px" OnChange="BuildActivityTypeSubTypeDropDown(this.value)"> <option value="">Select All</option> <option value=""></option> <option value="2" >Adventure</option> <option value="23" >Airborne</option> <option value="48" >Boot Camp</option> <option value="40" >Bowls</option> <option value="18" >Bridge</option> <option value="27" >Chess</option> <option value="47" >Comedy</option> <option value="21" >Cooking</option> <option value="37" >Creative Writing</option> <option value="25" >Cricket</option> <option value="38" >Croquet</option> <option value="4" >Culture</option> <option value="9" >Cycling</option> <option value="29" >Diving</option> <option value="39" >Drama</option> <option value="36" >Farming</option> <option value="12" >Fishing</option> <option value="6" >Fitness</option> <option value="19" >Football</option> <option value="13" >Golf</option> <option value="45" >Incentive</option> <option value="30" >Kayaking</option> <option value="15" >Languages</option> <option value="41" >Motorcycle</option> <option value="28" >Mountains</option> <option value="16" >Music</option> <option value="22" >Painting</option> <option value="5" >Personal Development</option> <option value="20" >Photography</option> <option value="17" >Poker</option> <option value="33" >Riding</option> <option value="32" >Sailing</option> <option value="26" >Scrabble</option> <option value="35" >Singing</option> <option value="8" selected>Ski</option> <option value="46" >Spice</option> <option value="3" >Sport</option> <option value="10" >Surfing</option> <option value="11" >Tennis</option> <option value="14" >Walking</option> <option value="7" >Wellbeing</option> <option value="42" >Wildlife</option> <option value="31" >Windsurfing</option> <option value="24" >Wine</option> </select> <br><br> Activity Type<br> <select id="ActivitySubTypeDropDown" name="ActivitySubTypeId" style="width: 100px"> </select> <SCRIPT LANGUAGE="JavaScript"> <!-- Begin BuildActivityTypeSubTypeDropDown(8); // End --> </script> <br><br> <input type="submit" value="Search Bookings" class="button"> </form> </body> </html> I'm looking for the most minimal changes necessary to get it to work in current desktop versions of Edge, Firefox and Chrome. I should add that this is HTML output. The contents of the arrays on lines 11 to 15 are pulled from a database with server side code, so if possible I'm looking for an answer which continues to use these arrays. When I remove the compatibility meta tag I get the following error alert for line 20: "Unable to get property "options" of undefined or null reference". Can anyone help?
There is no element with ID ActivitySubTypeId. You should change var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') to var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeDropDown')
Adding more information to #Titus' answer: From MS documentation you can see that In IE7 Standards mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results. For more information, see Defining Document Compatibility. So forcing the compatibility mode that code works because of the name attribute, but any modern browser checks just the id attribute's value, as expected.
You should need to change this, it will also give the error in other browsers var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') to var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeDropDown');
Using IF statements in a form to narrow choices down
I basically want to limit my choices in my form so that when a car is chosen as well as the transmission only certain colors may appear. I have created the form. The problem is creating the code in the Javascript file. I don't know how to make it so that if Car 1 is chosen as well as Automatic then for example only Black and blue appear as options. Im relatively new to coding and any help would be appreciated. Thanks HTML <script src="Script\configurator.js" type="text/javascript"></script> <form name="CarConfigurator"> <select name="Car_make" onchange="Transmission(this.value);"> <option value=" " selected="selected">None</option> <option value="1">Audi RS6</option> <option value="2">BMW M4</option> <option value="3">Mercedes C63 AMG</option> </select> <br> <br> <select name="A_M" > <option value="" selected="selected">None</option> <option value="1" selected="selected">Automatic</option> <option value="2" selected="selected">Manual</option> </select> <br> <br> <select name="Color"> <option value="" selected="selected">None</option> <option value="1">Black</option> <option value="2">Blue</option> <option value="3">Red</option> <option value="4">White</option> <option value="5">Green</option> </select> </form> Javascript function Transmission(Car) { var make = document.CarConfigurator.A_M; make.options.length = 0; if (Car == "1") { make.options[make.options.length] = new Option('Automatic','1'); make.options[make.options.length] = new Option ('Manual','2'); } if (Car =="2" ) { make.options[make.options.length] = new Option('Manual','2'); } if (Car == "3") { make.options[make.options.length] = new Option('Automatic','3'); } }
Is this what you want: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form name="CarConfigurator"> <select name="Car_make" onchange="Transmission();"> <option value=" " selected="selected">None</option> <option value="1">Audi RS6</option> <option value="2">BMW M4</option> <option value="3">Mercedes C63 AMG</option> </select> <br> <br> <select name="A_M" onchange="Transmission();"> <option value="" selected="selected">None</option> <option value="1" selected="selected">Automatic</option> <option value="2" selected="selected">Manual</option> </select> <br> <br> <select name="Color" onchange="ChoicesMade();"> <option value="" selected="selected">None</option> <option value="1">Black</option> <option value="2">Blue</option> <option value="3">Red</option> <option value="4">White</option> <option value="5">Green</option> </select> <div id="imageContainer" style="display: none;"><img src="http://buyersguide.caranddriver.com/media/assets/submodel/6873.jpg" /></div> </form> <script type="text/javascript"> function Transmission() { var Car = document.CarConfigurator.Car_make.value; var make = document.CarConfigurator.A_M.value; var color = document.CarConfigurator.Color; color.options.length = 0; if (Car == "1" && make == '1') { color.options.add(new Option('Black', '1')); color.options.add(new Option('Blue', '2')); } else if(Car == '2' && make == '1') { color.options.add(new Option('Red', '3')); color.options.add(new Option('White', '4')); } ChoicesMade(); } function ChoicesMade() { var form = document.CarConfigurator; var car = form.Car_make.value; var make = form.A_M.value; var color = form.Color.value; if(car != ' ' && make != '' && color != '') { var imageContainer = document.querySelector('#imageContainer'); imageContainer.style.display = 'block'; } } </script> </body> </html>
You can use objects in JavaScript and then loop through each array in object to change options. For example var cars = { "Audi_RS6":{ "name":"Audi RS6", "Automatic":["color_1","color_2"], "Manual":["color_1","color_2"] }, "BMW_M4":{ "name":"BMW M4", "Manual":["color_1","color_2"] }, "Mercedes_C63_AMG":{ "name":"Mercedes C63 AMG", "Automatic":["color_1","color_2"] } }; values can be accessed like this var result = cars.Audi_RS6.Manual[1];
Here you go Duncher, this code does exactly what you want <!DOCTYPE html> <html><head> <title></title> </head> <body> <form name="CarConfigurator"> <select id="car" name="Car_make"> <option value="" selected="selected">Which car?</option> <option value="car1">Audi RS6</option> <option value="car2">BMW M4</option> <option value="car3">Mercedes C63 AMG</option> </select> <br> <br> <select id="trans" name="A_M"> <option value="" selected="selected">What trans?</option> <option value="auto">Automatic</option> <option value="man">Manual</option> </select> <br> <br> <select id="color" name="Color"> <option value="" selected="selected">What Color?</option> <option value="black">Black</option> <option value="blue">Blue</option> <option value="red">Red</option> <option value="white">White</option> <option value="green">Green</option> </select> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="configurator.js"></script> </body> </html> And the JavaScript: $("#car").change(function () { transmission(); }); $("#trans").change(function () { transmission(); }); function transmission() { if ($("#car").val() == "car1" && $("#trans").val() == "auto") { $("option[value$='red']").hide(); $("option[value$='white']").hide(); $("option[value$='green']").hide(); } else { $("option[value$='red']").show(); $("option[value$='white']").show(); $("option[value$='green']").show(); } } You will have to make a few tweaks to get your other car & trans combinations working how you want them to (i.e. displaying only the colors you want) by adding more if else statements in the transmission() method but this should get you on your way. This is using jQuery by the way. Screen shot
Html/Javascript form calculation and validation in new page
I'm working on a website project and really need help as I'm new to all this. I'm basically given values to every option in the drop down menu's and make them add together which I've managed. But then I want to the total value from the menus to then be the range for a pseudo random to be a generated and added to the age I input. When I hit submit I'd like it to calculate all that and display the result on a new page. I want to be able to do all this within javascript and html. Any help would be greatly appreciated! My coding is below. Thanks so much! <body> <form id="form1" action="" method="post" onsubmit="return calcTotal(this)"> <select name=select1> <option selected="selected" value="0">Chinese Zodiac</option> <option value="3">Rat</option> <option value="3">Ox</option> <option value="4">Tiger</option> <option value="2">Rabbit</option> <option value="4">Dragon</option> <option value="5">Snake</option> <option value="3">Horse</option> <option value="3">Sheep</option> <option value="4">Monkey</option> <option value="5">Rooster</option> <option value="3">Dog</option> <option value="3">Pig</option> </select> </select> <br /> <select name=select2> <option selected="selected" value="0">Star Sign</option> <option value="2">Aries</option> <option value="4">Taurus</option> <option value="3">Gemini</option> <option value="4">Cancer</option> <option value="3">Leo</option> <option value="2">Virgo</option> <option value="2">Libra</option> <option value="3">Scorpio</option> <option value="2">Sagittarius</option> <option value="4">Capricorn</option> <option value="2">Aquarius</option> <option value="3">Pisces</option> </select> <br /> <select name=select3> <option selected="selected" value="0">Blood Type</option> <option value="3">O</option> <option value="2">A</option> <option value="1">B</option> <option value="3">AB</option> </select> <br /> <select name=select4> <option selected="selected" value="0">Favourite Colour</option> <option value="3">Black</option> <option value="3">Blue</option> <option value="2">Brown</option> <option value="2">Green</option> <option value="3">Orange</option> <option value="3">Pink</option> <option value="2">Purple</option> <option value="4">Red</option> <option value="2">Yellow</option> <option value="2">White</option> <option value="5">Other</option> </select> <br /> Age<input name="" type="number" value="" /> <br /> <input name="" type="submit" value="Total" /> <span>Total: </span><span id="result"></span> </form> <script type="text/javascript"> function calcTotal(oForm){ var sum = 0; for(i=0; i < oSels.length; i++){ sum += new Number(oSels[i].value); } document.getElementById('result').innerHTML = sum; return false; } window.onload=function(){ oSels = document.getElementById('form1').getElementsByTagName('select'); for(i=0; i < oSels.length; i++){ oSels[i].onchange=function(){ document.getElementById('result').innerHTML = ''; } } } </script>
I played with your code. I don't now if it's someting like that that you wanted but here is an example of random score. It now use the age to generate a value. Take a look if you like it at my codepen. I changed the age input: Age<input id="age" name="" type="number" value="" /> I also added a new function to generate random number between min-max: function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } And modified how the sum is calculated: var age = document.getElementById('age').value; sum = parseInt(age) + parseInt(getRandomInt(sum-(age / 4),sum+(age / 4))); //Add some random. The more you are older, the more random it is. You can do a lot of different generated sum. If you want less modifications, we also can take the last digit of the age to get the min/max value generated... Edit: To help you share variables between pages, Look at this question.
Adding this as an answer as the submitter considers it a good idea: Put the result from all your maths into hidden fields. Then when you submit the form, the values will be passed along. You don't need to do anything special really. Just add fields like this: <input type="hidden" value="[yourValue]" name="fieldName" id="fieldId" /> For the yourValue part, simply insert your caclulated value from the JavaScript: document.getElementById("fieldId").value = calculatedValue; Since it's all part of the same form that you're submitting anyway, they will all be past along. You can retrieve the fields on the receiving page as normal. I downloaded and edited your entire code block. I changed a couple of things. 1. You don't need the onsubmit on your form. You need a call the JavaScript function on a Total button. The submit button is added to submit the form when the user is done. 2. A hidden field to hold your result is added to the form. 3. The function where you do your calculation has an addition to send the calulated total to the new hidden field. 4. You need to add something to the ACTION, so it knows where to submit the form. You can also remove the ALERT. I just added that to be sure it worked right. I've run and tested this, and it works exactly as expected. This is what the edited code looks like: <body> <form id="form1" action="" method="post"> <select name=select1> <option selected="selected" value="0">Chinese Zodiac</option> <option value="3">Rat</option> <option value="3">Ox</option> <option value="4">Tiger</option> <option value="2">Rabbit</option> <option value="4">Dragon</option> <option value="5">Snake</option> <option value="3">Horse</option> <option value="3">Sheep</option> <option value="4">Monkey</option> <option value="5">Rooster</option> <option value="3">Dog</option> <option value="3">Pig</option> </select> </select> <br /> <select name=select2> <option selected="selected" value="0">Star Sign</option> <option value="2">Aries</option> <option value="4">Taurus</option> <option value="3">Gemini</option> <option value="4">Cancer</option> <option value="3">Leo</option> <option value="2">Virgo</option> <option value="2">Libra</option> <option value="3">Scorpio</option> <option value="2">Sagittarius</option> <option value="4">Capricorn</option> <option value="2">Aquarius</option> <option value="3">Pisces</option> </select> <br /> <select name=select3> <option selected="selected" value="0">Blood Type</option> <option value="3">O</option> <option value="2">A</option> <option value="1">B</option> <option value="3">AB</option> </select> <br /> <select name=select4> <option selected="selected" value="0">Favourite Colour</option> <option value="3">Black</option> <option value="3">Blue</option> <option value="2">Brown</option> <option value="2">Green</option> <option value="3">Orange</option> <option value="3">Pink</option> <option value="2">Purple</option> <option value="4">Red</option> <option value="2">Yellow</option> <option value="2">White</option> <option value="5">Other</option> </select> <br /> Age<input name="" type="number" value="" /> <br /> <input name="" type="button" value="Total" onclick="calcTotal();" /> <input name="submit" type="submit" value="Submit" /> <span>Total: </span><span id="result"></span> <input type="hidden" value="0" name="resultIs" id="resultIs" /> </form> <script type="text/javascript"> function calcTotal(oForm) { var sum = 0; for (i = 0; i < oSels.length; i++) { sum += new Number(oSels[i].value); } //This is what you are using to display the result to your user. document.getElementById('result').innerHTML = sum; //This will add the value of the result to a hidden field I added to the form. When you submit it, just request the value of "resultIs" document.getElementById("resultIs").value = sum; alert(sum); return false; } //I really don't even see that this is needed. Your form doesn't need to be cleared onLoad. window.onload = function() { oSels = document.getElementById('form1').getElementsByTagName('select'); for (i = 0; i < oSels.length; i++) { oSels[i].onchange = function() { document.getElementById('result').innerHTML = ''; } } } </script>