Unable to print sum of function in js - javascript

What I want my program to do:
I'm trying to make an online order form in html/java script. Within my select element, there are 3 options, each with a different price. I am trying to let the user select one of the options, choose the quantity they want, then display the total price.
Problem
The total price wont display.
What I've tried
I have create in internal js script, and create a function getChoice. Using if statements, I am checking to see which option the user selected and depending on which one is selected, I am multiplying the value's price by the quantity of the item they want, and trying to return this value to "total".
<script>
var choice = document.getElementById("burgerSize").value;
var amount = document.getElementById("quantity").value;
function(getTotalAmount){
if(choice === "4"){
document.getElementById("total").value=
amount*4;
}
if(choice === "6"){
document.getElementById("total").value=
amount*6;
}
if(choice === "10"){
document.getElementById("total").value=
amount*10;
}
}
</script>
My HTML code:
Please select size:
<select id="burgerSize" onchange="getTotalAmount()">
<option disabled="disabled" selected = "selected" Select option</option>
<option value="4">Large </option>
<option value="6">Extra-Large </option>
<option value="10">Supersize </option>
</select>
<label for="quantity"> Quantity: </label>
<input type="number" id="quantity" name="quantity" min=1><br>
<label> Total cost: </label>
<input type="text" id ="total"/><br>
</form><br><br>
<script>
Any pointers in the right direction would be really appreciated! Thanks in advance

You can easily make this working by doing something like calling the function when the user give values to the input fields.
function totalCal(){
const choice = document.getElementById("burgerSize").value;
const amount = document.getElementById("quantity").value;
document.getElementById("total").value = amount * choice;
}
document.getElementById("burgerSize").oninput = ( function(event) {
totalCal();
});
document.getElementById("quantity").oninput = ( function(event) {
totalCal();
});
<form>
<label for="burgerSize">Please select size:</label>
<select id="burgerSize">
<option disabled="disabled" selected="selected">Select option</option>
<option value="4">Large </option>
<option value="6">Extra-Large </option>
<option value="10">Supersize </option>
</select>
<label for="quantity"> Quantity: </label>
<input type="number" id="quantity" name="quantity" min=1><br>
<label> Total cost: </label>
<input type="text" id="total" /><br>
</form>
It will be better if you add greater than sign (">") at the end of the first option tag and also to get the total's value, you can multiply amount and choice according to this program.
Thanks and best regards!

Related

JavaScript : How to get selected dropdown value?

I'm using code from w3schools & attempting to modify it so that the script will multiply by a different valNum based on the value selected from the drop down list. So if All Purpose Flour is selected the Output = Input multiplied by 4.409245; for Cane Sugar it would be Output = Input multiplied by 8.82.
Here's what I have so far. I plan to add more option values to the list but need help figuring out how to do this. I'm new to JavaSript; sorry if this looks odd. Any feedback is appreciated. Thanks!
<select name="ingredients" id="ingredients">
<option value="flour">All Purpose Flour</option>
<option value="sugar">Cane Sugar</option>
</select>
<p>
<label>Pounds</label>
<input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter(this.value)" onchange="weightConverter(this.value)">
</p>
<p>Ounces: <span id="outputOunces"></span></p>
<script>
function weightConverter(valNum) {
document.getElementById("outputOunces").innerHTML=valNum*4.409245;
}
</script>
Updated your code with a few pointers -
To add another option, say Cheese with multiplier of 2, you can just add the option in the HTML under the select element and add a new case in the switch statement as shown in the below code.
Have added the method weightConverter for the onChange of the select component for the case when user enters some value first in the input box and then decides to change their mind and change the value in the select component, it re-evaluates the Output after changing the option in the select component.
<select name="ingredients" id="ingredients" onChange="weightConverter()">
<option value="flour">All Purpose Flour</option>
<option value="sugar">Cane Sugar</option>
<option value="cheese">Cheese</option>
</select>
<p>
<label>Pounds:</label>
<input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter()">
</p>
<p>Ounces: <span id="outputOunces"></span></p>
<script>
function weightConverter() {
const dropDownValue = document.getElementById('ingredients').value;
const valNum = document.getElementById('inputPounds').value;
let multiplier = 0;
switch (dropDownValue) {
case 'flour':
multiplier = 4.409245;
break;
case 'sugar':
multiplier = 8.82;
break;
case 'cheese':
multiplier = 2;
break;
default:
break;
}
document.getElementById("outputOunces").innerHTML = valNum * multiplier;
}
</script>
You can try below snippet.
function selectionChange() {
weightConverter(document.getElementById("inputPounds").value);
}
function weightConverter(valNum) {
if (document.getElementById("ingredients").value == "flour"){
document.getElementById("outputOunces").innerHTML = (valNum * 4.409245).toFixed(6);
}
else{
document.getElementById("outputOunces").innerHTML=(valNum*8.82).toFixed(6);
}
}
<select name="ingredients" id="ingredients" onchange="selectionChange()">
<option value="flour">All Purpose Flour</option>
<option value="sugar">Cane Sugar</option>
</select>
<p>
<label>Pounds</label>
<input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter(this.value)">
</p>
<p>Ounces: <span id="outputOunces">0.000000</span></p>
Please use this code.
function selectionChange() {
weightConverter(document.getElementById("inputPounds").value);
}
function weightConverter(valNum) {
if (document.getElementById("ingredients").value == "flour")
document.getElementById("outputOunces").innerHTML = valNum * 4.409245;
else
document.getElementById("outputOunces").innerHTML = valNum * 8.82;
}
<select name="ingredients" id="ingredients" onchange="selectionChange()">
<option value="flour">All Purpose Flour</option>
<option value="sugar">Cane Sugar</option>
</select>
<p>
<label>Pounds</label>
<input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter(this.value)" onchange="weightConverter(this.value)">
</p>
<p>Ounces: <span id="outputOunces"></span></p>

How can I calculate a number in an input field with a value from a dropdown menu?

I'm trying to create a calculator-like program that takes the number you enter into the first input field and divides it by the number in the dropdown field below it. I'm trying to get a specific percentage of whatever number is entered in the first field.
However, I keep getting "NaN" when it runs. What should I change?
const number = document.getElementById('number');
const percentageSelector = document.getElementById('percentageSelector');
const submitButton = document.getElementById('submitButton');
//The mathematical stuff
submitButton.addEventListener('click', () => {
alert(number * percentageSelector);
});
<h2>Enter number here</h2>
<input type="number" id="number">
<h2>Select a percentage to divide by</h2>
<select id="percentageSelector">
<option selected disabled>Pick one</option>
<option>1%</option>
<option>2%</option>
<option>3%</option>
<option>4%</option>
<option>5%</option>
<option>6%</option>
<option>7%</option>
<option>8%</option>
<option>9%</option>
<option>10%</option>
</select>
<button type="submit" id="submitButton">Submit</button>
The following code ensures that the value of the inputs only get checked when the button is clicked. Values have also been added to each option and the value of the percentageSelector is checked using percentageSelector.selectedOptions[0].value.
I have also made a jsfiddle.
const percentageSelector = document.getElementById('percentageSelector');
const submitButton = document.getElementById('submitButton');
//The mathematical stuff
submitButton.addEventListener('click', () => {
const number = document.getElementById('number').value;
const percentage = percentageSelector.selectedOptions[0].value;
alert(number * percentage);
});
<h2>Enter number here</h2>
<input type="number" id="number">
<h2>Select a percentage to divide by</h2>
<select id="percentageSelector">
<option selected disabled>Pick one</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.1">10%</option>
</select>
<button type="submit" id="submitButton">Submit</button>
This const percentageSelector = document.getElementById('percentageSelector'); sets percentageSelector to the element not the value of the element. (Ditto "number").
Since the operands are set outside the click function, they will have the values as when the page loaded. You probably want to collect that info after the click, ie inside the function.
The value of a select element is the option that has been selected. The value is going to be the value attribute of the option. But none of the options has a value. Once you add values (as with <option value=".01">, it should be able to "do the math".
so simple.. take care to use numbers and not string values
const numberIn = document.getElementById('number-in')
, percent = document.getElementById('percentage-Selector')
, btCompute = document.getElementById('submit-Button')
;
btCompute.onclick=()=>
{
console.log('percent=', numberIn.valueAsNumber *Number(percent.value) /100)
}
<h2>Enter number here</h2>
<input type="number" id="number-in">
<h2>Select a percentage to divide by</h2>
<select id="percentage-Selector">
<option selected disabled>Pick one</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>
<button id="submit-Button">Submit</button>

Text box not changes for default drop down value in javascript

I have a txtSubTotal text box, a discount drop down and a txtGrossTotal text box. txtSubTotal text box is updating when the ADD button is clicked. txtGrossTotal text box is updating when the drop down value is selected. But, when updating the txtSubTotal text box, at the same time txtGrossTotal text box should be updated for the default drop down value, which is "0". Here, txtGrossTotal should be the value of txtSubTotal.
Below is my code, it doesn't display the txtGrossTotal when the drop down has it's default value. (But, after selecting another option, and again select the default value, it updates the txtGrossTotal.)
function discountedGrossTotal(dropdownVal){
var discountOption = document.getElementById("discount"),
subTotal = document.getElementById("txtSubTotal"),
grossTotal = document.getElementById("txtGrossTotal").value;
grossTotal.value = subTotal.value - (subTotal.value * dropdownVal/100);}
discount drop down
<select class="select" id="discount" name="discount" onchange="discountedGrossTotal(this.value);">
<option selected>0</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
txtGrossTotal HTML
<div id="gross_total_div">
<input name="txtGrossTotal" type="text" id="txtGrossTotal" size="15" readonly/>
</div>
Basically you want to take the same action by changing the "discount" dropdown value as well as the "subtotal" textbox value. So, you will have to call the same function on both.
You can achieve this by doing below modifications in your code:
Remove the parameters from "discountedGrossTotal" function
Add a new variable inside your function like dropdownVal = document.getElementById("discount").value
Call the same function on change event of your "txtSubTotal" textbox
Now, this function will be called if any of these (textbox or dropdown) value is changed and hence the "Gross Total" value will be updated accordingly.
Please Try this, it should work for you...
function discountedGrossTotal() {
var dropdownVal= document.getElementById("discount").options[document.getElementById("discount").selectedIndex].innerHTML;
subTotal = document.getElementById("txtSubTotal");
grossTotal = document.getElementById("txtGrossTotal").value;
document.getElementById("txtGrossTotal").value = subTotal.value - (subTotal.value * dropdownVal / 100);
}
sub total: <input type="text" id="txtSubTotal" onblur="discountedGrossTotal()" />
<br />
discount: <select class="select" id="discount" name="discount" onchange="discountedGrossTotal();">
<option selected>0</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br />
<div id="gross_total_div">
<input name="txtGrossTotal" type="text" id="txtGrossTotal" size="15" readonly />
</div>

Jquery Select field populates Input field

I am trying to Select one of the options from the drop-down and populate the input field with the correct values.
I want to set the value 1 to ($100) val 2 to ($200)
I will not have access to a database to store the values.
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name=
"costfield">
<option value="Select Country"> Select Country</option>
<option value="1"> country 1</option>
<option value="2"> country 2</option>
<option value="1"> country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="estimate" class="form-control" id="exampleInputEstimate1" placeholder="Estimate">
</div>
</div>
<script>
$( "#costfield" ).val();
$( "#estimate" ).text( "this" ).show();
</script>
</div>
You can store the values in the HTML5 data- attribute for each <option> element. This approach is useful when there is no direct relationship between the option's value attribute and the dollar value you are assigning it to.
p/s: type="estimate" is not a valid attribute value. Try type="text" (anyway, browsers will parse invalid type into text automagically.
// Listen to change
$('#costfield').change(function() {
$('#exampleInputEstimate1').val($(this).find('option:selected').data('dollar-value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name="costfield">
<option value="Select Country">Select Country</option>
<option value="1" data-dollar-value="$100">country 1</option>
<option value="2" data-dollar-value="$200">country 2</option>
<option value="1" data-dollar-value="$100">country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="exampleInputEstimate1" placeholder="Estimate" />
</div>
$('[name="costfield"]').change(function () {
console.log("test");
var cost = this.value;
var str = "";
switch (cost) {
case "1":
str = "$100";
break;
case "2":
str = "$200";
break;
}
$("#exampleInputEstimate1").val(str);
});
JSFiddle
You could use jQuery to get the value from the Select when it changes and then change the value of the input accordingly. So put this in between the script tags.
$('#costfield').on('change', function() {
var value = $(this).val();
$('#exampleInputEstimate1').val(value);
});
You can either set your option values to be 100 or 200 then on any change in the drop down set the value of your input to the value.
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val());
} );
If you want to keep your option values as they are then you can still use the same as above with a small change. (on the assumption that 1 will be 100, 2 will be 200, 3 will be 300, and so on)
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val() + "00" );
} );
Also you may want to put a new option and set it as blank with no value that way you force the user to select something. Or you can set the input on document load and keep the number of options you have. AKA:
<option value="" ></option>

Don't display number greater than 72

I have a sample site here.
In the bottom of the document, there's a section labeled 'Potential Gen Ed TOC'.
If you open the Accordion labeled Composition, you'll see dropdown menus on the right.
As you can see, in this JavaScript, it was based on whether or not a checkbox was activated. Then the 'Potential Gen Ed TOC' would display a number based on the assigned value.
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() {
sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#total_potential').html(sum);
});
});
As you continue to check boxes throughout the different courses, a sum would be displayed.
What' I'm trying to do now, is eliminate the checkbox trigger in the JS. I've replaced them with dropdown menus that say, "Credits - Select Credit".
Whenever someone selects a value, the "Potential Gen Ed TOC" slowly increases based on that value.
I would assume that all I have to do is assign value="Any Number" and the JavaScript would pick up on that.
In the JavaScript (above), I'm having trouble accounting for pulling these values from the dropdown menus. As you can see the JS is based on checked boxes.
Once I'm able to pull values from the dropdown menu, I want to have these values add up, but never display a number higher than 72, no matter how many total transfer credits are selected.
Does that make sense?
Edit: Here is some markup to understand where I'm trying to pull the values from (dropdown menu)...
<fieldset name = Comunication>
<legend>Transfer Course Information</legend>
<label for="School Int.">School Int.</label>
<input name="School Int." type="text" size="6" maxlength="6" />
<label for="ID">ID</label>
<input name="ID" type="text" id="ID" size="8" />
<label for="Name">Name</label>
<input name="Name" type="text" id="Name" size="25" />
<label for="Grade">Grade</label>
<input name="Grade" type="text" id="Grade" size="2" />
<label for="COM1"></label>
<form id="form2" name="form2" method="post" action="">
<label for="Credits">Credits</label>
<select name="Credits" id="Credits">
<option value="0">Select Credit</option>
<option value="0.67">1 QtrCr.</option>
<option value="1.33">2 QtrCr.</option>
<option value="2.00">3 QtrCr.</option>
<option value="2.67">4 QtrCr.</option>
<option value="3.33">5 QtrCr.</option>
<option value="4.00">6 QtrCr.</option>
<option value="4.67">7 QtrCr.</option>
<option value="5.33">8 QrtCr.</option>
<option value="6.00">9 QtrCr.</option>
<option value="6.67">10 QtrCr.</option>
<option value="1">1 SemCr.</option>
<option value="2">2 SemCr. </option>
<option value="3">3 SemCr.</option>
<option value="4">4 SemCr.</option>
<option value="5">5 SemCr.</option>
<option value="6">6 SemCr.</option>
<option value="7">7 SemCr. </option>
<option value="8">8 SemCr.</option>
<option value="9">9 SemCr.</option>
<option value="10">10 SemCr.</option>
</select>
</form>
Transferrable
<input name="COM105" type="checkbox" id="COM1" />
$('#total_potential').html(Math.min(sum,72));
Will display the sum up to 72 then just 72
Here's how you would do it with select inputs:
$(function($) {
$('#CourseMenu select').change(function() {
var sum = 0;
$('#CourseMenu select').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
$('#total_potential').html(Math.min(sum,72));
});
});
Important note
You have some serious issues with your form HTML markup. You have repeating ids in some of your elements which represents invalid markup, id attributes must be unique in a page. Also some of your inputs have the same name, which mean only one value will be submitted with the form. You can use arrays in your inputs name to submit multiple values.
how about:
if (sum <= 72) {
$('#total_potential').html(sum);
} else {
$('#total_potential').html("72");
}

Categories

Resources