I have made this function here to calculate prices from choices in the select menu. I have made a switch but I dont understand where to input my function to trigger it (on html). The 2 other functions changeit() and changerepas() are onchange functions that will give you the basic price. (they are not linked to the question) (Note: This is my first switch ever, so it might look noobish to most of you. )
function taxesrepas(option){
var soustot;
var taxes;
var taxer;
var taxetotal = taxes + taxer;
var total = taxetotal + soustot;
var pricee;
var pricer;
var soustot = pricee + pricer;
switch (option){
case "spaghetti":
taxer = 0.69;
pricer = 8.95
break;
case "lasagne":
taxer = 0.75;
pricer = 9.95;
break;
case "salade":
taxes = 0.45;
pricee = 5.95;
break;
case "escargot":
taxes = 0.38;
pricee = 4.95;
break;
}
document.getElementById("taxes").innerHTML = taxetotal;
document.getElementbyid("total").innerHTML = total;
document.getElementbyid("soustot").innerHTML = soustot;
}
<select name="entree" id="entree" onChange="changeit(this.value)">
<option value="hidden" selected>Choisir...</option>
<option value="salade">Salade</option>
<option value="escargot">Escargot</option>
</select>
<img display="inline" id="imgselect" src="" alt="0.00$"/>
<h3 id= "choix1"></h3>
<p>Repas</p>
<select name="repas" id="repas" onChange="changerepas(this.value)">
<option value="hidden1" selected>Choisir...</option>
<option value="spaghetti">Spaghetti</option>
<option value="lasagne">Lasagne</option>
</select>
<h3 id="choix"></h3>
<h3 id="taxes"></h3>
<h3 id="soustotal"></h3>
<h3 id="total"></h3>
Maybe change the onChange to
function(){
taxesrepas(this.value);
changeit(this.value);
}
Related
I want to if you select an option on the brandSelect, the option on the socketSelect will appear, and I have a code like this
<select id="brandSelect" onchange="brandSelect()">
<option value="10">Pilih Brand</option>
<option value="20">AMD</option>
<option value="30">Intel</option>
</select>
<select id="socketSelect">
<option>Pilih Socket</option>
</select>
and
function brandSelect(){
var x = document.getElementById("brandSelect");
var selectedValue = x.options[x.selectedIndex].value;
switch(selectedValue){
case 10:
break;
case 20:
var x = document.getElementById("socketSelect");
var am4 = document.createElement("option");
var am3 = document.createElement("option");
var am2 = document.createElement("option");
am4.text = "AM4";
am3.text = "AM3";
am2.text = "AM2";
x.add(am4);
x.add(am3);
x.add(am2);
break;
case 30:
break;
}
}
And why my code still won't work?
Your code does not work because in javascript, switch compare value using === which checks for both data type and value, and the value from x.options[x.selectedIndex].value; is string type while you compare with int type. You have to convert your value to integer type before comparing using switch.
<select id="brandSelect" onchange="brandSelect()">
<option value="10">Pilih Brand</option>
<option value="20">AMD</option>
<option value="30">Intel</option>
</select>
<select id="socketSelect">
<option>Pilih Socket</option>
</select>
<script type="text/javascript">
function brandSelect(){
var x = document.getElementById("brandSelect");
var selectedValue = parseInt(x.options[x.selectedIndex].value); //parse your value to integer
switch(selectedValue) {
case 10:
break;
case 20:
var y = document.getElementById("socketSelect");
var am4 = document.createElement("option");
var am3 = document.createElement("option");
var am2 = document.createElement("option");
am4.text = "AM4";
am3.text = "AM3";
am2.text = "AM2";
y.add(am4);
y.add(am3);
y.add(am2);
break;
case 30:
break;
}
}
</script>
Demo: https://jsfiddle.net/t7umjq2y/
I have this function that is supposed to return taxes, total and total before taxes of a choice in a select menu. This is the function:
var select = document.getElementById('entree');
select.addEventListener('change', function() {
taxesrepas(select.value);
});
function taxesrepas(option) {
var soustot = 0,
taxes = 0,
total = 0,
soustot = 0;
if (option == "spaghetti") {
total += 9.62;
taxes += 0.67;
soustot += 8.95;
}
if (option == "lasagne") {
total += 10.70;
taxes += 0.75;
soustot += 9.95;
}
if (option == "salade") {
total += 6.30;
taxes += 0.45;
soustot += 5.95;
}
if (option == "escargot") {
total += 5.32;
taxes += 0.37;
soustot += 4.95;
}
document.getElementById("taxes").innerHTML = taxes;
document.getElementById("total").innerHTML = total;
document.getElementById("soustotal").innerHTML = soustot;
}
I want to return the results in these tags, but they simply wont return. Also I dont know how to launch the function, I tried with onchange/onload, but nothing is returning!
<h3>taxes:</h3><span id="taxes"></span>
<h3>Sous-total:</h3><span id="soustot"></span>
<h3>Total:</h3><span id="total"></span>
Thank you for your help
EDIT1: The select option comes from 2 separate menu where lasagna/spaghetti are together and salade/escargot are in another. I need this function to addd both prices and taxes and print it in those h3.
Here are the 2 select menus:
<select name="repas" id="entree2" onChange="changerepas(this.value)">
<option value="hidden1" selected>Choisir...</option>
<option value="spaghetti">Spaghetti</option>
<option value="lasagne">Lasagne</option>
</select>
<select name="entree" id="entree3" onChange="changeit(this.value)">
<option value="hidden" selected>Choisir...</option>
<option value="salade">Salade</option>
<option value="escargot">Escargot</option>
</select>
just a little example based on your, you got some problem on init variable ... regards.
document.querySelector('select').addEventListener('change', function() {
taxesrepas(this.value);
});
https://codepen.io/anon/pen/OxjjYv
I'm starting to develop websites (learning from 0). Of course, I apologize for my healthy ignorance (and my english level).
I have 3 select in descending order: the 1st one contains a list of options that are loaded from a database (for now, I only load from HTML). Depending on the option selected, the 2nd select will be loaded with its options and so on until a 3rd select. The problem itself is solved, but when you want to select the options already loaded in the 2nd select, do not "click" on them. Only allows you to select the first one option. Here I leave the code to see if anyone can find any possible solution (and a lot of errors ^^).
var carsAndModels = {};
carsAndModels['Volvo'] = ['V70', 'XC60'];
carsAndModels['Volkswagen'] = ['Golf', 'Polo'];
carsAndModels['BMW'] = ['M6', 'X5'];
var speedsAndModels = {};
speedsAndModels['V70'] = ['150km/h', '180km/h'];
speedsAndModels['XC60'] = ['160km/h', '190km/h'];
speedsAndModels['Golf'] = ['170km/h', '190km/h'];
speedsAndModels['Polo'] = ['180km/h', '200km/h'];
speedsAndModels['M6'] = ['190km/h', '2000km/h'];
speedsAndModels['X5'] = ['200km/h', '210km/h'];
function ChangeCarList() {
var carList = document.getElementById('car');
var modelList = document.getElementById('carmodel');
var speedList = document.getElementById('speed');
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
speedList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i+1);
modelList.options.add(car);
}
}
ChangeModelList();
}
function ChangeModelList() {
var modelListM = document.getElementById('carmodel');
var speedListM = document.getElementById('speed');
var indMod = modelListM.selectedIndex;
var selMod = modelListM.options[indMod].text;
while (speedListM.options.length) {
speedListM.remove(0);
}
var speeds = speedsAndModels[selMod];
if (speeds) {
for (i = 0; i < speeds.length; i++) {
var speed = new Option(speeds[i], i+1);
speedListM.options.add(speed);
}
}
}
<div class="">
<div class="">
<span>Select the brand</span><hr>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Select --</option>
<option value="Volvo">Volvo</option>
<option value="Volkswagen">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
</div>
<div class="">
<span>Select the model</span><hr>
<select id="carmodel" onchange="ChangeCarList()"></select>
</div>
<div class="">
<span>Select the speed control</span><hr>
<select id="speed"></select>
</div>
</div>
question: How to call the functions ("ChangeCarList" & "ChangeModelList") through the standard W3Schools in an external file?
Thank you very much :).
The reason it is not working is because you are removing the options on selecting a different option. You need to remember the selected option in index like below. You may have to tidy up your solution even more but this solution will let select other options.
Notice this added part in solution I propose.
var index;
if (value) {
index = modelList.selectedIndex;
}
Here old index is being remembered. Here the option is selected based on remembered index, once you are done with adding options.
modelList.selectedIndex = index;//<----This also is required
var carsAndModels = {};
carsAndModels['Volvo'] = ['V70', 'XC60'];
carsAndModels['Volkswagen'] = ['Golf', 'Polo'];
carsAndModels['BMW'] = ['M6', 'X5'];
var speedsAndModels = {};
speedsAndModels['V70'] = ['150km/h', '180km/h'];
speedsAndModels['XC60'] = ['160km/h', '190km/h'];
speedsAndModels['Golf'] = ['170km/h', '190km/h'];
speedsAndModels['Polo'] = ['180km/h', '200km/h'];
speedsAndModels['M6'] = ['190km/h', '2000km/h'];
speedsAndModels['X5'] = ['200km/h', '210km/h'];
function ChangeCarList(value) {
var carList = document.getElementById('car');
var modelList = document.getElementById('carmodel');
var speedList = document.getElementById('speed');
var selCar = carList.options[carList.selectedIndex].value;
var index;
if (value) {
index = modelList.selectedIndex;
}
while (modelList.options.length) {
modelList.remove(0);
speedList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i + 1);
modelList.options.add(car);
}
}
modelList.selectedIndex = index;
ChangeModelList();
}
function ChangeModelList() {
var modelListM = document.getElementById('carmodel');
var speedListM = document.getElementById('speed');
var indMod = modelListM.selectedIndex;
var selMod = modelListM.options[indMod].text;
while (speedListM.options.length) {
speedListM.remove(0);
}
var speeds = speedsAndModels[selMod];
if (speeds) {
for (i = 0; i < speeds.length; i++) {
var speed = new Option(speeds[i], i + 1);
speedListM.options.add(speed);
}
}
}
<div class="">
<div class="">
<span>Select the brand</span>
<hr>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Select --</option>
<option value="Volvo">Volvo</option>
<option value="Volkswagen">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
</div>
<div class="">
<span>Select the model</span>
<hr>
<select id="carmodel" onchange="ChangeCarList(this.value)"></select>
</div>
<div class="">
<span>Select the speed control</span>
<hr>
<select id="speed"></select>
</div>
</div>
So I have this project where I have to make a clothing store and I want to do the following:
I have this code in html:
<select class="sizeb" style="display: none;">
<option value="xxs">XXS</option>
<option value="xs">XS</option>
<option value="s">S</option>
<option value="m">M</option>
<option value="l">L</option>
<option value="xl">XL</option>
<option value="xxl">XXL</option>
</select>
and with JavaScript I want to take the option value, check it's value and create a var price; then check and set a price:
var x = <somehow to get the value>;
if (x == 'xxs')
price = 5;
else if(x == 'xs')
price = 10;
and display it later this way:
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
Any help is appreciated.
First, you just get a reference to the HTML element and assign that to a variable:
var select = document.querySelector(".sizeb");
Then you get the value:
var val = select.value;
Then you do your logic and calculations:
var x = <somehow to get the value>;
if (x == 'xxs'){
price = 5;
} else if(x == 'xs') {
price = 10;
}
And, then display the result:
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
NOTE: You have your select to be hidden initially. If that's the case, no one will ever be able to select a value from it.
Now, you also have to decide "when" you want all this to be done. That could be when the value in the select changes. BUt, if that's the case, you should add a first option of something like --- Select One ---, because if the user wants the first selection, they won't do anything, which won't trigger the change event. So, putting it all together, we get:
// Get a reference to the select
var select = document.querySelector(".sizeb");
// Set up an event handler that runs when the value in the select changes:
select.addEventListener("change", function(){
// Then you get the value:
var x = select.value;
var price = null;
// Then you do your logic and calculations.
// And if will work, but for this a switch is better
switch (x) {
case 'xxs' :
price = 5;
break;
case 'xs' :
price = 10;
break;
case 's' :
price = 15;
break;
case 'm' :
price = 20;
break;
case 'l' :
price = 25;
break;
case 'xl' :
price = 30;
break;
case 'xxl' :
price = 35;
break;
}
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
});
<select class="sizeb">
<option value="">--- Select One ---</option>
<option value="xxs">XXS</option>
<option value="xs">XS</option>
<option value="s">S</option>
<option value="m">M</option>
<option value="l">L</option>
<option value="xl">XL</option>
<option value="xxl">XXL</option>
</select>
<div id="PriceTag"></div>
You can:
1-Add an listener to the select like this
<select onchange="someFunction(this)" class="sizeb" style="display: none;>
2-create a function like this:
function someFunction(element){
va price = element.value;
document.getElementById("PriceTag").innerHTML = "Pret: " + price + " RON";
}
Could anyone help me figure out a better way of returning the right message based on my if...else logic? So I'm trying to calculate a student's GPA via dropdown menus. Each letter is your standard fare (A = 4.0, B = 3.5, etc). Now, if a student has a calculated GPA that is >= 3.5, I want to display a certain message. If It's anything lower, I'd display another message. I'm having a hard time figuring out how to print the message based on the condition.
function letterToGrade(gpa){
var grade;
switch (gpa)
{
case "A": grade = 4.0;
break;
case "B": grade = 3.0;
break;
case "C": grade = 2.0;
break;
case "D": grade = 1.0;
break;
case "F": grade = 0.0;
break;
}
return grade;
}
function calculateGPA(){
var numOfRequisites = 5;
var gpa1 = letterToGrade(document.getElementById("Foundation").value);
var gpa2 = letterToGrade(document.getElementById("Database").value);
var gpa3 = letterToGrade(document.getElementById("Elect").value);
var gpa4 = letterToGrade(document.getElementById("Commerce").value);
var gpa5 = letterToGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
var result = "<p>Your calculated GPA is: "+(gpaTotal.toFixed(1))+"<br></p>";
if (gpaTotal >= 3.5)
return result += "<p>Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program.</p>";
else
return result += "<p>Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time.</p>";
document.getElementById("result").innerHTML=result;
}
And here's the HTML. Not all of it.
<h4>Thank you for your interest in our summer internship program. Please enter your GPA for the following courses. </h4>
<p>
IT 3503 Foundation of HIT:
<select id="Foundation">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4153 Advanced Database:
<select id="Database">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4513 Elect Health Rec Sys & Ap:
<select id="Elect">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4123 Electronic Commerce:
<select id="Commerce">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4533 Health Info Sec & Priv:
<select id="HealthInfo">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
</form>
<input type="button" value="Submit" onclick="calculateGPA()" />
</p>
The last part kind of messes me up. I'm pretty new to HTML and Javascript. This is for a school assignment, so please feel free to insult me as you will for being a slacker.
you have several problems
grade is never defined
you return before the other code can be executed
numGrade is undefined. probably mean for CalculateGPA to be numGrade, or vise versa
So
function CalculateGPA(){
//grade here is undefined as it isnt declared before here
switch (grade) {
case "A":
grade = 4.0;
break;
case "B":
grade = 3.0;
break;
case "C":
grade = 2.0;
break;
case "D":
grade = 1.0;
break;
case "F":
grade = 0.0;
break;
}
return grade; //you return here so any code after this is never executed
var numOfRequisites = 5;
var gpa1 = numGrade(document.getElementById("Foundation").value);
var gpa2 = numGrade(document.getElementById("Database").value);
var gpa3 = numGrade(document.getElementById("Elect").value);
var gpa4 = numGrade(document.getElementById("Commerce").value);
var gpa5 = numGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
if (gpaTotal >= 3.5)
return acceptanceMessage;
else
return consolationMessage;
//document.getElementById("result").innerHTML=message;
}
i think you want:
function numGrade(gpa){
switch (gpa) {
case "A": gpa = 4.0;
break;
case "B": gpa = 3.0;
break;
case "C": gpa = 2.0;
break;
case "D": gpa = 1.0;
break;
case "F": gpa = 0.0;
break;
}
return gpa;
}
function calculateGradeAndGenMessage(){
var numOfRequisites = 5;
var gpa1 = numGrade(document.getElementById("Foundation").value);
var gpa2 = numGrade(document.getElementById("Database").value);
var gpa3 = numGrade(document.getElementById("Elect").value);
var gpa4 = numGrade(document.getElementById("Commerce").value);
var gpa5 = numGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
if (gpaTotal >= 3.5)
return acceptanceMessage;
else
return consolationMessage;
}
document.getElementById("result").innerHTML=calculateGradeAndGenMessage();
As stated in the comments, you never defined gpa. However, I noticed you wanted to clean up your code a bit...I recommend going about this by breaking it up into two functions:
DEMO:
http://jsfiddle.net/dirtyd77/Q86gt/4/
JAVASCRIPT:
//Calculate average GPA of 5 classes.
//If avereage GPA >= 3.5, show acceptance message.
//Else thank for applying.
var consolationMessage = "<p>Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time.";
var acceptanceMessage = "Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program."
//get the gpa
function getGPA() {
var gpaTotal = null,
message = null,
classes = ['Foundation', 'Database', 'Elect', 'Commerce', 'HealthInfo'];
//iterate over classes
for (var i = 0; i < classes.length; i++) {
var gpa = calculateGPA(document.getElementById(classes[i]).value);
gpaTotal += gpa;
}
//gpaTotal divided by number of classes
gpaTotal /= classes.length;
//if not all values are filled out, alert and return
if (isNaN(gpaTotal)) {
alert('Please fill out all answers!');
return;
}
if (gpaTotal >= 3.5) message = acceptanceMessage;
else message = consolationMessage;
document.getElementById("result").innerHTML = message;
}
function calculateGPA(gpa) {
switch (gpa) {
case "A":
gpa = 4.0;
break;
case "B":
gpa = 3.0;
break;
case "C":
gpa = 2.0;
break;
case "D":
gpa = 1.0;
break;
case "F":
gpa = 0.0;
break;
}
return gpa;
}
HTML:
<h4>Thank you for your interest in our summer internship program. Please enter your GPA for the following courses. </h4>
<p>IT 3503 Foundation of HIT:</p>
<select id="Foundation">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4153 Advanced Database:</p>
<select id="Database">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4513 Elect Health Rec Sys & Ap:</p>
<select id="Elect">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4123 Electronic Commerce:</p>
<select id="Commerce">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4533 Health Info Sec & Priv:</p>
<select id="HealthInfo">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<input type="button" value="Submit" onclick="getGPA()" />
<p id="result"></p>
Hope this helps and let me know if you have any questions.
I missed this return statement originally but you return gpa after your switch statement.
This will cause your function to end as it has been returned already.
Then after return gpa you have two other unnecessary return statements in your if block.
You should break up the calculation of the GPA and the message generation separately.
function calculateGPA(letterGrade) {
var gpa;
switch (letterGrade) {
case 'A':
gpa = 4.0;
break;
case 'B':
gpa = 3.0;
break;
case 'C':
gpa = 2.0;
break;
case 'D':
gpa = 1.0;
break;
case 'F':
gpa = 0.0;
break;
}
return gpa;
}
function averageGPA() {
var gpas = [],
sum = 0,
numberGPA;
gpas.push(calculateGPA(document.getElementById("Foundation").value));
gpas.push(calculateGPA(document.getElementById("Database").value));
gpas.push(calculateGPA(document.getElementById("Elect").value));
gpas.push(calculateGPA(document.getElementById("Commerce").value));
gpas.push(calculateGPA(document.getElementById("HealthInfo").value));
for (var i = gpas.length - 1; i >= 0; i--) {
sum += gpas[i]
};
return sum / gpas.length;
}
function passMessage(gpa) {
var result = document.getElementById('result'),
message;
if (gpa >= 3.5) {
message = "Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program.";
} else if (gpa < 3.5) {
message = "Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time";
}
result.innerHTML = message;
}
function checkGPAResults() {
passMessage(averageGPA());
}
And a fiddle