I'm a little confused about why my code doesn't work. I'm very new and am extremely interested to know where I went wrong!
I want to times whichever option I choose by var z but can't get it to work.
This is my code so far:
<td><select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select></td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
<script>
function myFunction() {
var y = document.getElementById("VAS").value;
var z = document.getElementById("number").value;
var a = document.getElementById("VGS").value;
var c = document.getElementById("VAF").value;
var d = document.getElementById("VTS").value;
if (value == VGS) {
var x = a * z;
document.getElementById("value").innerHTML = x;
}
else if (value == VAS) {
var x = y * z;
document.getElementById("value").innerHTML = x;
}
}
</script>
You need to compare the value of the select, not the values of the options. Here's how I fixed your JavaScript code:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
Fully working demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
EDIT:
To do this automatically, use oninput in the number field like so:
<input type="number" id="number" name="number" oninput="myFunction()" />
Demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number" oninput="myFunction()">
</td>
<td>
<br/>
<br/>
<p id="value"></p>
Your values are numbers, so value will never contain VAS. Furthermore, strings need to be surrounded by quotes, so your if-statement will look like this:
if(a == "VAS")
But the value contains numbers, so it should actually be:
if(a == "40")
Note: the values are all strings unless you cast them.
Related
I'm trying to multiply value pass from input tag type number by value pass from select tag.
<div>
<input type="number" value="0" id="input" name="word_count" value="500" style="text-align: center;" />
<select id="work" onchange="myFunction();" name="work">
<option>-Select-</option>
<option value="article">Article</option>
</select>
</div>
function myFunction() {
var x = document.getElementById("work").value;
if (document.getElementById("work").value == "article") {
var w = 5;
if (document.getElementById("input")) {
var x = document.getElementById("input").value;
var wc = w * x;
document.getElementById("total_amount").value = +wc;
document.getElementById("np").value = +wc;
}
}
}
You didn't have tags with id total_amount and np. I added them to the HTML. (I added <span></span> tags, so I changed the value to textContent at the end of the conditional)
You redeclared var x (and redefined it) in your conditional - I renamed it to z (it might not have caused a problem, but just to be sure). Actually if you'd done it with the let keyword, it would've thrown an exception).
function myFunction() {
var x = document.getElementById("work").value;
console.log(x)
if (document.getElementById("work").value == "article") {
var w = 5;
if (document.getElementById("input")) {
// renamed x to z
var z = document.getElementById("input").value;
var wc = w * z;
// not .value but .textContent
document.getElementById("total_amount").textContent = +wc;
document.getElementById("np").textContent = +wc;
}
}
}
<div>
<input type="number" value="0" id="input" name="word_count" value="500" style="text-align: center;" />
<select id="work" onchange="myFunction();" name="work">
<option disabled selected>-Select-</option>
<option value="article">Article</option>
</select>
</div>
Total amount: <span id="total_amount"></span><br /> NP: <span id="np"></span>
Here's the scenario: the user inputs two numbers in each box, and chooses from the box Min, Max, and pow. Numbers are unlimited, which are entered by keyboard, it could be any integer, and the result should either be Max/Min/Pow. I already have my option box, and layout ready, but I cannot get my results as it either gives a 'NaN' or nothing at all.
Can someone please help in finding out the error in my code?
<script>
function calc(){
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var oper = document.getElementById('operators').value;
if(oper === 'min')
{
document.getElementById('result').value = Math.min;
}
}
</script>
<select id="operators">
<option value="min">Math.min</option>
<option value="max">Math.max</option>
<option value="pow">Math.pow</option>
</select>
<input type="text" id="num1" value="">
<input type="text" id="num2" value="">
<button onclick="calc();">Evaluate 2 input function</button>
<br><br>
You need to provide arguments to Math.min()
document.getElementById('result').value = Math.min(num1, num2)
See code snippet:
function calc() {
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var oper = document.getElementById('operators').value;
if (oper === 'min')
document.getElementById('result').innerText = Math.min(num1, num2);
else if (oper === 'max')
document.getElementById('result').innerText = Math.max(num1, num2);
else
document.getElementById('result').innerText = Math.pow(num1, num2);
}
<select id="operators">
<option value="min">Math.min</option>
<option value="max">Math.max</option>
<option value="pow">Math.pow</option>
</select>
<input type="text" id="num1" value="">
<input type="text" id="num2" value="">
<button onclick="calc();">Evaluate 2 input function</button>
<br><br>
<h1 id="result"></h1>
Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}
I am trying to add two functions calculate1() and calculate2(). Both functions are taking values from function populate(). Is the code wrong? Once I enter an amount on both functions, the result is total amount undefined.
<form>
Car:
<select id="slct1" name="slct1" onchange="populate('slct1','slct2')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Car:
<select id="slct2" name="slct2">
</select>
<label> Amount <input style="width:10%" type="number" name="amount1" id="amount1" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer1" id="answer1"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
</form>
<!--Starts 2 selection-->
<form>
Food:
<select id="slct1a" name="slct1a" onchange="populate('slct1a','slct2a')">
<option value=""></option>
<option value="Fiat">Fiat</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Type of Food:
<select id="slct2a" name="slct2a">
</select>
<label> Amount <input style="width:10%" type="number" name="amount2" id="amount2" onkeyup="result()"/> (g) </label>
<label> Total <input style="width:10%" type="number" name="answer2" id="answer2"/></label>
<input type="reset" name="Reset" value="Reset" onclick="rstFunction()"/>
<br><br><br>
<hr>
<br>
<p id="ansCAL"></p>
</form>
<input type="reset" onclick="resetFunctions()" value="Reset">
</script>
var t = total1 + total2;
function result() {
document.getElementById('ansCAL').value = calculate1() + calculate2();
}
function populate(select1, select2)
{
var Brand1 = document.getElementById(select1);
var Brand2 = document.getElementById(select2);
Brand2.innerHTML = "";
if(Brand1.value == "Fiat")
{
var optionArray = ["|","4000|Uno","5000|Ritmo","6000|Panda"];
}
else if(Brand1.value == "Dodge")
{
var optionArray = ["|","4000|Avanger","5000|Challengere","6000|Charger"];
}
else if(Brand1.value == "Ford")
{
var optionArray = ["|","7000|Mustang","8000|Shelby","focus|Focus"];
}
for(var option in optionArray)//the options within the optionArray
{
var pair = optionArray[option].split("|");//in tha variable pair is stored both value and label
var newOption = document.createElement("option");// option in the bracket is used to create new options or you can insert divs paragraph etc
newOption.value = pair[0];//pair 0 gives the value
newOption.innerHTML = pair[1];//pair 1 gives the label
Brand2.options.add(newOption);
}
}
function calculate1() {
Brand1 = document.getElementById('slct1').value;
Brand2 = document.getElementById('slct2').value;
multi=document.getElementById('amount1').value;
total1=parseInt((Brand2)*multi/100);
document.getElementById('answer1').value=total1;
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function calculate2() {
Brand1 = document.getElementById('slct1a').value;
Brand2 = document.getElementById('slct2a').value;
multi=document.getElementById('amount2').value;/*to change accordingly amount1*/
total2=parseInt(((Brand2)*multi)/100);
document.getElementById('answer2').value=total2;/*to change accordingly amount1*/
document.getElementById("ansCAL").innerHTML = "<br>Total amount " + t;
}
function resetFunctions() {
//using the array forEach method on the form
Array.prototype.forEach.call(document.forms,function(el,idx,array){
//the method parameters are element, index and the array
// we loop through all the forms and invoking reset()
el.reset();
});
result();
}
function rstFunction()
{
document.getElementById("ansCAL").innerHTML = "<br>Total amount" + result().value;
}
</script>
The answer was to increase the total in every calculate function. Example (total + total1). Removed the variable t and declared the totals in the printout section.
I am trying to create a simple cost Estimator in HTML Javascript but I am having trouble calling a JS function with a HTML Button. I know the problem must be due to how I am calling my function or how I am displaying the result of the calculation, or both.
If any one could show me where I am going wrong and what is the correct practise it would be greatly appreciated.
Here is the Codepen: http://codepen.io/FredHair/pen/FgJAd
(It returns Undefined for the answer).
This is my HTML:
<div>
<h1>Cost Estimator</h1>
<form>
<input type= "numbers" id="x" placeholder = "Length" /><br />
<input type= "numbers" id="y" placeholder = "Width"/><br />
<input type= "numbers" id="z" placeholder = "Height"/><br />
<select id="choice" >
<option value = "" ></option>
<option value = "1">option 1</option>
<option value = "2">0ption 2</option>
<option value = "3">option 3</option>
</select>
<br/>
<br/>
<input id= "est" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>
<h1 id="result"> = </h1>
</div>
This Is the JS:
function calculator(calc){
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
var p = Number(30);
var result;
switch(calc){
case"1" : result = z * p;
break;
case"2" : result = x * p + 50;
break;
case"3" : result = x * p + 30;
break;
}
document.getElementById("result").innerHTML = " = " + result;
}
http://codepen.io/FredHair/pen/FgJAd
Thanks.
function calculator() {
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
var p = Number(30);
var result;
var calc = document.getElementById("choice").value
switch (calc) {
case "1":
result = z * p;
break;
case "2":
result = x * p + 50;
break;
case "3":
result = x * p + 30;
break;
}
document.getElementById("result").innerHTML = " = " + result;
}
<div>
<h1>Cost Estimator</h1>
<form>
<input type="numbers" id="x" placeholder="Length" />
<br />
<input type="numbers" id="y" placeholder="Width" />
<br />
<input type="numbers" id="z" placeholder="Height" />
<br />
<select id="choice">
<option value=""></option>
<option value="1">option 1</option>
<option value="2">0ption 2</option>
<option value="3">option 3</option>
</select>
<br/>
<br/>
<input id="est" type="button" value="Estimate" onclick="calculator()" />
<input id="reset" type="reset" value="Reset" />
</form>
<h1 id="result"> = </h1>
</div>
You are not passing the value calc...
update your js code like this:
function calculator(){
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
var p = Number(30);
var result;
var calc = document.getElementById("choice").value
switch(calc){
case"1" : result = z * p;
break;
case"2" : result = x * p + 50;
break;
case"3" : result = x * p + 30;
break;
}
Instead get the value of calc in parameter get it under the method.