JavaScript : How to get selected dropdown value? - javascript

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>

Related

How do I use the compute() event properly for a calculator

I'm trying to code a sample rate calculator and I need the compute() function to display text with certain parameters each time it's pressed, but it's not working
I'll paste the code samples below.
var principal = document.getElementById("principal").value;
var rate = document.getElementById("rate").value;
var years = document.getElementById("years").value;
var interest = principal * years * rate /100;
var year = new Date().getFullYear()+parseInt(years);
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = "If you deposit "+principal+",\<br\>at an interest rate of "+rate+"%\<br\>You will receive an amount of "+amount+",\<br\>in the year "+year+"\<br\>";
}
function checkdata() {
//create references to the input elements we wish to validate
var years = document.getElementById("years");
var principal = document.getElementById("Principal");
//Check if "No of Years" field is actual year
if (years.value != "year") {
alert("Please input the actual year");
years.focus();
return false;
}
//Check if principal field is zero or negative
if (principal.value == "0" || principal.value == "negativ no") {
alert("Enter a positive number");
principal.focus();
return false;
}
//If all is well return true.
alert("Form validation is successful.")
return true;
}
function updateValue(event) {
document.getElementById("rate_val").innerText = event.value;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
<title>Simple Interest Calculator</title>
</head>
<body>
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount"></label>
Amount <input type="number" id="principal">
<br/>
<br/>
<label for="Interest Rate"></label>
<label for="Interest Rate">Interest Rate</label>
<input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
<span id="rate_val">10.25%</span>
<br/>
<br/>
<label for="No. of Years"></label>
No. of Years <select id="years">
<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>
<!-- fill in the rest of the values-->
</select>
<br/>
<br/>
<label for="Compute Interest"></label>
<button onclick="compute()">Compute Interest</button>
<br/>
<br/>
<span id="result"></span>
<br/>
<br/>
</form>
<br/>
<br/>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
</body>
</html>
The main issue in your code is because you've attached the onclick attribute to the button which submits the form. As the form submission is not being prevented, the page is redirected before you can update the DOM.
To fix this, hook the event handler to the submit event of the form and call preventDefault() on the event which is passed to the handler as an argument.
In addition, there's some other issues in your code.
You should avoid using onX attributes as they are no longer good practice. Attach your event handlers using unobtrusive JS, such as addEventListener().
amount is not defined anywhere. You will need to declare and set this variable. I've used a dummy value for it in the code below.
You need to retrieve the value properties of your form controls when the button is clicked, not when the page loads. This is to ensure that the values the user enters are retrieved from the DOM.
Wrap the field controls and the label text within the label element. Leaving them empty serves no purpose.
Avoid using the <br /> tag as much as possible. Given the above change to your label elements, apply CSS to add the margin underneath them instead.
In the checkData() function, years is a selection of integer values, so comparing those values to a "year" string is redundant.
In addition, to detect a negative number compare it to < 0, not the string "negative no"
With all that said, try this:
let principalEl = document.querySelector("#principal");
let rateEl = document.querySelector("#rate");
let rateOutputEl = document.querySelector('#rate_val');
let yearsEl = document.querySelector("#years");
let formEl = document.querySelector('#form1');
let result = document.querySelector('#result');
let amount = '???';
formEl.addEventListener('submit', e => {
e.preventDefault();
if (!checkData())
return;
let principal = principalEl.value;
let rate = rateEl.value;
let year = yearsEl.value;
let interest = principal.value * years.value * rate.value / 100;
let endYear = new Date().getFullYear() + parseInt(years.value);
result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
});
rateEl.addEventListener('input', e => {
rateOutputEl.textContent = e.target.value + '%';
});
function checkData() {
let principal = principalEl.value;
if (!principal || parseFloat(principal) < 0) {
alert("Enter a positive number");
principalEl.focus();
return false;
}
return true;
}
label {
display: block;
margin-bottom: 20px;
}
form {
margin-bottom: 50px;
}
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount">
Amount
<input type="number" id="principal">
</label>
<label for="Interest Rate">Interest Rate
<input type="range" id="rate" min="1" max="20" step="0.25" value="10.25" />
<span id="rate_val">10.25%</span>
</label>
<label for="No. of Years">
No. of Years
<select id="years">
<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>
<!-- fill in the rest of the values-->
</select>
</label>
<label for="Compute Interest">
<button type="submit">Compute Interest</button>
</label>
<span id="result"></span>
</form>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = ~If you deposit ${principal} at an ${interest} rate of ${rate}% You will receive an amount of ${amount} in the year ${year}~;
}

Unable to print sum of function in js

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!

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>

How do I implement a "Submit" button on a Javascript/HTML calculation form?

I want to add a "Submit" button in order to execute the formula after submit is pressed, but I can't seem to connect the submit button to the code to make the total emissions update only when the button is pressed.
When you input a vehicle type and miles driven and press somewhere else on the page, the total emissions updates. I'm trying to implement a 'submit' or 'calculate' button so that the total emissions only updates when the button is clicked.
I'd also like to wrap the Javascript in a function rather than window.onload, but I'm not sure how to implement that either.
window.onload = function () {
var carType = document.getElementById('VehicleType');
var total = document.getElementById('totalEmissions');
var miles = document.getElementById('milesDriven');
carType.onchange = function(){
if(miles.value){
total.value = parseFloat(carType.value) * parseFloat(miles.value);
}
if(!miles.value || !carType.value){
total.value = "";
}
};
miles.onchange = function () {
if(miles.value && carType.value){
total.value = parseFloat(carType.value) * parseFloat(miles.value)
}
if(!miles.value || !carType.value){
total.value = "";
}
};
};
<strong>Car Type</strong></th><br>
<select name="VehicleType" id="VehicleType">
<option value="">Select an option…</option>
<option value="552">Sprinter Van</option>
<option value="444">Personal Car</option>
<option value="444">Renter Car</option>
<option value="140">Bus or Shuttle</option>
<option value="727">Diesel Truck</option>
<option value="683">Regular Truck</option>
</select>
<br><br>
<strong>Miles Driven</strong></th><br>
<td width="65"><input type="text" name="milesDriven" id="milesDriven" size="15" maxlength="5"/></td>
<td width="43">miles</td>
<br><br>
<strong>Total CO2 Emissions (grams)</strong><br>
<td><input type="text" name="totalEmissions" id="totalEmissions" size="15" maxlength="5"/></td>
What you need is not a submit button, but a regular <button> element. Just create one, give it an id, then listen for its click event, instead of change events of the other two elements. Check for validity inside the function that you execute when it's clicked and show the result, like this:
window.onload = function() {
var carType = document.getElementById('VehicleType');
var total = document.getElementById('totalEmissions');
var miles = document.getElementById('milesDriven');
var calculateButton = document.getElementById('calculateButton');
calculateButton.addEventListener('click', calculate);
function calculate() {
if (miles.value && carType.value) {
total.value = parseFloat(carType.value) * parseFloat(miles.value);
}
if (!miles.value || !carType.value) {
total.value = "";
}
};
};
<strong>Car Type</strong><br>
<select name="VehicleType" id="VehicleType">
<option value="">Select an option…</option>
<option value="552">Sprinter Van</option>
<option value="444">Personal Car</option>
<option value="444">Renter Car</option>
<option value="140">Bus or Shuttle</option>
<option value="727">Diesel Truck</option>
<option value="683">Regular Truck</option>
</select>
<br><br>
<strong>Miles Driven</strong><br>
<input type="text" name="milesDriven" id="milesDriven" size="15" maxlength="5" /> miles
<br><br>
<strong>Total CO2 Emissions (grams)</strong><br><input type="text" name="totalEmissions" id="totalEmissions" size="15" maxlength="5" />
<br><br>
<button id="calculateButton">Calculate</button>
Note 1: As #ScottMarcus pointed out in the comments, instead of using onXyz, it's better to use .addEventListener(eventName, callback).
Note 2: I would suggest rechecking your HTML, if this is not part of something bigger, as there are a few problems I can see (which I fixed in my snippet). The W3C Markup Validation Service is a great place to check for problems in your markup.

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>

Categories

Resources