I'm using switch construction instead of if statement because I have more than one repeated statements where if statement doesn't wrong.
But it couldn't be calculated properly. Where am I wrong? The switch construction is not working. I used the console and the function sumUpNewCar worked right.
Therefore, I would like to execute all the sums in the box
function sprSelection() {
var sprCompleted = document.getElementById("sprCompleted");
var sprDoesntCompleted = document.getElementById("sprDoesntCompleted");
if(sprCompleted.checked) {
sprDoesntCompleted.disabled = true;
}
else if(sprDoesntCompleted.checked) {
sprCompleted.disabled = true;
}
else {
sprDoesntCompleted.disabled = false;
sprCompleted.disabled = false;
}
}
function prNewVehicleSelection (){
var twentyFiveCompleted = document.getElementById("twentyFiveCompleted");
var thirtyCompleted = document.getElementById("thirtyCompleted");
var thirtyFiveCompleted = document.getElementById("thirtyFiveCompleted");
if(twentyFiveCompleted.checked) {
thirtyCompleted.disabled = true;
thirtyFiveCompleted.disabled = true;
}
else if(thirtyCompleted.checked) {
twentyFiveCompleted.disabled = true;
thirtyFiveCompleted.disabled = true;
}
else if(thirtyFiveCompleted.checked) {
twentyFiveCompleted.disabled = true;
thirtyCompleted.disabled = true;
}
else {
twentyFiveCompleted.disabled = false;
thirtyCompleted.disabled = false;
thirtyFiveCompleted.disabled = false;
}
}
function sumUpNewCar(){
var promoLoan = Number (document.getElementById("promoLoan").innerHTML);
var standardLoan = Number (document.getElementById("newAuto2").innerHTML);
var promoPlusLoan = Number (document.getElementById("newAuto3").innerHTML);
var standardPlusLoan = Number (document.getElementById("newAuto4").innerHTML);
var twentyFiveCompleted = document.getElementById("twentyFiveCompleted");
var thirtyCompleted = document.getElementById("thirtyCompleted");
var thirtyFiveCompleted = document.getElementById("thirtyFiveCompleted");
var sprCompleted = document.getElementById("sprCompleted");
var sprDoesntCompleted = document.getElementById("sprDoesntCompleted");
var qualityCompleted = document.getElementById("qualityCompleted");
var qualityDoesntCompleted = document.getElementById("qualityDoesntCompleted");
var sumPromoLoansBonus = Number (document.getElementById("sumPromoLoansBonus").innerHTML);
var sumPromoPlusLoansBonus = Number (document.getElementById("sumPromoPlusLoansBonus").innerHTML);
var sumStandardLoansBonus = Number (document.getElementById("sumStandardLoansBonus").innerHTML);
var sumStandardPlusLoansBonus = Number (document.getElementById("sumStandardPlusLoansBonus").innerHTML);
var sumNewVehicle = Number (document.getElementById("sumNewVehicle").innerHTML);
switch(sumNewVehicle) {
case twentyFiveCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.0155));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0289));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0321));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.0432));
break;
case thirtyCompleted.checked:
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0321));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.054321));
break;
case thirtyFiveCompleted.checked:
sumPromoLoansBonus= Math.round (Number(promoLoan * 0.01234));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0321));
sumStandardLoansBonus= Math.round (Number (standardLoan * 0.066));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.7888));
break;
case sprCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.01222));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.028989));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.02111));
sumStandardPlusLoansBonus = Math.round (Number(standardPlusLoan * 0.041111));
break;
case sprCompleted.checked && twentyFiveCompleted.checked:
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.047868));
sumStandardPlusLoansBonus= Math.round (Number(standardPlusLoan * 0.056555));
break;
case sprCompleted.checked && thirtyFiveCompleted.checked:
sumPromoLoansBonus = Math.round (Number(promoLoan * 0.02222));
sumPromoPlusLoansBonus = Math.round (Number (promoPlusLoan * 0.0345));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.04445));
sumStandardPlusLoansBonus= Math.round (Number(standardPlusLoan * 0.0667);
break;
default:
sumPromoLoansBonus = Math.round (Number (promoLoan * 0.0015));
sumPromoPlusLoansBonus= Math.round (Number (promoPlusLoan * 0.0244));
sumStandardLoansBonus = Math.round (Number (standardLoan * 0.0244));
sumStandardPlusLoansBonus = Math.round (Number (standardPlusLoan * 0.03511));
break;
}
}
function calculate(){
var sumPromoLoansBonus = Number (document.getElementById("sumPromoLoansBonus").innerHTML);
var sumPromoPlusLoansBonus = Number (document.getElementById("sumPromoPlusLoansBonus").innerHTML);
var sumStandardLoansBonus = Number (document.getElementById("sumStandardLoansBonus").innerHTML);
var sumStandardPlusLoansBonus = Number (document.getElementById("sumStandardPlusLoansBonus").innerHTML);
var sumNewVehicle = document.getElementById("sumNewVehicle").innerHTML = Number (sumPromoLoansBonus + sumPromoPlusLoansBonus + sumStandardLoansBonus + sumStandardPlusLoansBonus );
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>revenue calculator Version 7</title>
</head>
<body>
<!--BOX #1-->
<div class="mainbox">
<form >
<input class="promo" type="number" min="1000" max="100000000" id="promoLoan" onchange="sumUpNewCar()">
<input class="standard" type="number" min="100000" max="100000000" id="newAuto2" onchange="sumUpNewCar()">
<input class="promoPlus" type="number" min="100000" max="100000000" id="newAuto3" onchange="sumUpNewCar()">
<input class="standardPlus" type="number" min="100000" max="100000000" id="newAuto4" onchange="sumUpNewCar()">
</form>
</div>
<!--BOX #2-->
<div class="mainbox2">
<label class="container4"><b>25%</b>
<input type="checkbox" class="input1" id="twentyFiveCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container4"><b>30%</b>
<input type="checkbox" class="input1" id="thirtyCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container4"><b>35%</b>
<input type="checkbox" class="input1" id="thirtyFiveCompleted" onclick="prNewVehicleSelection(), sumUpNewCar(), calculate()">
</label>
<label class="container" for="yes"><b> Да</b>
<input type="checkbox" class="input1" name="yes" id="sprCompleted" onclick="sprSelection(), sumUpNewCar()">
</label>
<label class="container" for="no"><b> Нет</b>
<input type="checkbox" class="input1" name="no" id="sprDoesntCompleted" onclick="sprSelection(), sumUpNewCar()">
</label>
<!--BOX#6-->
<div class="mainbox6">
<table class="tableOverall" >
<tr>
<td id="sumNewVehicle"></td>
</tr>
</table>
</div>
</div>
<table class="tableOverall2">
<tr>
<td id="sumPromoLoansBonus"></td> <!-- sum of promo box BASIC-->
<td id="sumPromoPlusLoansBonus"></td> <!-- sum of promoplus box BASIC-->
<td id="sumStandardLoansBonus"></td> <!-- sum of standard box BASIC-->
<td id="sumStandardPlusLoansBonus"></td> <!-- sum of standard plus box BASIC-->
</table>
What are the possible values that sumNewVehicle will has? It will return some number in your case.
Also what values that twentyFiveCompleted.checked will have? I guess it will give either True or False.
So if both these variables are having different values then your switch case will never work.
Secondly you are using "&&" condition in Switch case which is not accepted.
Even if twentyFiveCompleted.checked will return a Number then also due to "&&" condition in Switch case your switch case iteration won't work.
For example:- you are using
case sprCompleted.checked && twentyFiveCompleted.checked:
That is the case where you should use if clauses, instead of switch case.
It will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.Your comparison value is an integer, but most of your case expressions resolve to a boolean value. Mainly those functions where you have used "&&" conditions.
Refer this link for more info
javascript: using a condition in switch case
I think you need to check out the switch Case syntax :
switch(expression) {
case n:
code block1
break;
case m:
code block 2
break;
default:
code block 3
}
which is equivelant to :
if (expression == n) {
code block 1
}
else if (expression == m) {
code block 2
}
else {
code block 3
}
Related
That's my second script ever. I'm learning basics at the same time. I would like to engage different function on different option selected.
I try to give value to different option to use it later where the switch is.
It says cannot set property of null. If someone could explain me what I'm doing wrong it would be amazing. Please forgive me for silly mistakes, 3 days of learning in total, unfortunately theory doesn't work on me if i will not try it.
<html>
<body>
<div>
<h2> Daily calorie intake</h2>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"><p></p>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"><p></p>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"><p></p>
Your sex
<select name = "sex" id = "sex">
<option value = "1" id = "male">male</option>
<option value = "2" id = "female">female</select><p></p>
<button onclick="calculate()">Calculate</button>
</div>
<script>
var height = document.getElementById('height').onclick;
var age = document.getElementById('age').onclick;
var weight = document.getElementById('weight').onclick;
var sex = 1;
function calculate(height, age, weight, sex) {
switch(sex) {
case sex: 1
calculate = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age)
case sex: 2
calculate = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age)
break;
default: 1
}
document.getElementById('calculate').innerHTML = calculate
}
</script>
</body>
</html>
The error Uncaught TypeError: Cannot set property 'innerHTML' of null means that the object that you are calling .innerHTML on doesn't exist. In your case that's this line:
document.getElementById('calculate').innerHTML = calculate
and you get that error because you don't have an element with an id of calculate. If you don't have that element, you can't call .innerHTML on it.
You also need to get the data out of your form fields with the .value property, not the onclick property.
See additional comments below:
<html>
<head>
<title>Sample Page</title>
<style>
div { margin:1em; } /* adds vertical space before and after each div */
</style>
</head>
<body>
<div>
<!-- You can't have an <h2> if you don't already have an <h1> for it to be
a sub-section of. Don't use HTML elements because of how they style the output.
Use CSS to style. Also, don't use <p></p> to create vertical space. Again, use
CSS for style. -->
<h1> Daily calorie intake</h1>
<div><input type="number" placeholder="your height" id="height" min="1" max="230"></div>
<div><input type="number" placeholder="your age" id="age" min="1" max="120"></div>
<div><input type="number" placeholder="your weight" id="weight" min="1" max="500"></div>
<div>Your sex
<select id="sex">
<option value="1" id="male">male</option>
<option value="2" id="female">female</option>
</select>
</div>
<button>Calculate</button>
</div>
<div id="output"></div>
<script>
// Do your event binding in JavaScript, not in HTML
document.querySelector("button").addEventListener("click", calculate);
// Get references to the elements you'll need (not the value of their onclick properties)
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var sex = 1;
// You don't need any arguments because you already have references to the fields
// where the data is.
function calculate() {
// Declare the variable the will hold the result and don't use the
// name of the function as the name of the variable
let result = null;
switch(sex) {
// To get the data out of a form field, you must access its .value property
case sex: 1
result = 66.5 * (13.75 * weight.value) + (5 * height.value) - (6.76 * age.value);
break;
case sex: 2
result = 655.1 * (9.56 * weight.value) + (1.85 * height.value) - (4.68 * age.value);
break;
default: 1
}
// Make sure you reference elements that exist and don't use
// .innerHTML when there is no HTML in the string.
document.getElementById('output').textContent = result;
}
</script>
</body>
</html>
I hope this helps, this code is working
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var boton = document.getElementById('boton');
function calculate(height, age, weight, sex) {
switch(sex) {
case 1:
var calculo = 66.5 * (13.75 * weight) + (5 * height) - (6.76 * age);
break;
case 2:
var calculo = 655.1 * (9.56 * weight) + (1.85 * height) - (4.68 * age);
break;
default: 1
}
console.log(calculo);
return calculo;
}
boton.addEventListener('click', () => calculate(height.value, age.value, weight.value, 1));
<button id="boton"> Click me </button>
<input type = "number" placeholder = "your height" id = "height" min = "1" max = "230"/>
<input type = "number" placeholder = "your age" id = "age" min = "1" max = "120"/>
<input type = "number" placeholder = "your weight" id = "weight" min = "1" max = "500"/>
How to I restrict a number entering into input field (numeric) greater than another number using JavaScript?
I used:
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal").value;
var matricobtained = document.getElementById("matricobtained").value;
var intertotal = document.getElementById("intertotal").value;
var interobtained = document.getElementById("interobtained").value;
var bachelortotal = document.getElementById("bachelortotal").value;
var bachelorobtained = document.getElementById("bachelorobtained").value;
var mphilltotal = document.getElementById("mphilltotal").value;
var mphillobtained = document.getElementById("mphillobtained").value;
if (matricobtained > matrictotal || interobtained > intertotal || bachelorobtained > bachelortotal || mphillobtained > mphilltotal) {
alert("pleses provide obtained marks less then total marks");
e.returnValue = false;
e.preventDefault();
} else {
return true;
}
}
But after alert it allows number place in input field.
First, just get the object that represents each object then pass in the two methods into a helped method to do the actual comparison. If the values are not what you are looking for, then set the objects value to "" and highlight the textbox to show which one is wrong.
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal");
var matricobtained = document.getElementById("matricobtained");
var intertotal = document.getElementById("intertotal");
var interobtained = document.getElementById("interobtained");
var bachelortotal = document.getElementById("bachelortotal");
var bachelorobtained = document.getElementById("bachelorobtained");
var mphilltotal = document.getElementById("mphilltotal");
var mphillobtained = document.getElementById("mphillobtained");
checkValue(matrictotal, matricobtained);
checkValue(intertotal, interobtained);
checkValue(bachelortotal, bachelorobtained);
checkValue(mphilltotal, mphillobtained);
}
function checkValue(total, obtained){
if (obtained.value > total.value) {
alert("Please provide obtained marks less then total marks: " + obtained.id);
obtained.value = "";
obtained.classList.add("error");
} else {
obtained.classList.remove("error");
return true;
}
}
.error {
border: 2px solid #FF0000;
}
<label for="matrictotal">matrictotal</label>
<input type="text" id="matrictotal" value="10">
<label for="matricobtained">matricobtained</label>
<input type="text" id="matricobtained" value="10">
<br />
<label for="intertotal">intertotal</label>
<input type="text" id="intertotal" value="10">
<label for="interobtained">interobtained</label>
<input type="text" id="interobtained" value="10">
<br />
<label for="bachelortotal">bachelortotal</label>
<input type="text" id="bachelortotal" value="10">
<label for="bachelorobtained">bachelorobtained</label>
<input type="text" id="bachelorobtained" value="10">
<br />
<label for="mphilltotal">mphilltotal</label>
<input type="text" id="mphilltotal" value="10">
<label for="mphillobtained">mphillobtained</label>
<input type="text" id="mphillobtained" value="10">
<button onclick=numberalert(this)>Check values</button>
Note : In Javascript there is no strictly greater than or strictly less than comparator .
In case if you need strictly greater than use
(a !==b && a > b) (or) (!(a < b))
Similarly for strictly less than use
(a !== b && a < b) (or) (!(a>b))
var toCheckNumber = 100;
validate = function(el, event) {
var errorText = document.getElementById('errorText');
errorText.innerHTML = "";
var x = event.which;
var value = el.value;
var number = 0;
switch (x) {
case 48: number =0;break;
case 49: number = 1; break;
case 50: number = 2; break;
case 51: number = 3; break;
case 52: number = 4; break;
case 53: number = 5; break;
case 54: number = 6; break;
case 55: number = 7; break;
case 56: number = 8; break;
case 57: number = 9; break;
case 8: number = -1; break;
case 46: number = -1; break;
default : event.preventDefault(); return ;
}
var tempval = (number !== -1) ? value * 10 + number : value;
if (!(tempval < toCheckNumber)) {
event.preventDefault();
errorText.innerHTML = "Enter number less than " + toCheckNumber;
}
}
<input type="number" onkeydown="validate(this,event)" onchange="document.getElementById('errorText').innerHTML=''">
<div id="errorText" style="color:red"></div>
How can i operate 2 math operation inside jquery ?
result = val;
a = result * 5000;
b = result * 0.1;
result = a + b;
https://jsfiddle.net/7ugdjezb/
my codes didn't give the right result
function calculate() {
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var price = $('#price').val();
if (rege.test(price)) {
val = parseInt(price);
var result = val;
if ($('input[name="selectedItems1"]').is(":checked")) {
a = (result * 5000);
b = result * 0.1;
result = a + b;
} else {
result = result * 5000;
}
if (isNaN(result))
j.value = 0
else
j.value = result;
} else
alert("Error in input");
}
$(function() {
$('input[name="selectedItems1"]').change(function() {
calculate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form>
<input type="text" class="form-control" placeholder="Item Price" id="price" onkeyup="calculate()" />
<br />
<input type="checkbox" name="selectedItems1" value="val1" />Tax 10%
<br/>
<input type="text" id="output" value="Output" />
</form>
Here is a cleaned up version. Please note the
result += (result * 0.1); part
function calculate() {
var $outPut = $("#output"),
rege = /^[0-9]*$/,
price = $('#price').val() || 0,
result = 0;
if (!rege.test(price)) {
console.log("Error in input");
} else {
result = parseInt(price) * 5000;
if ($('input[name="selectedItems1"]').is(":checked")) {
result += (result * 0.1);
}
}
$outPut.val(result.toFixed(2));
}
$(function() {
$('#price').on("keyup",calculate);
$('input[name="selectedItems1"]').on("change",calculate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" class="form-control" placeholder="Item Price" id="price" />
<br />
<input type="checkbox" name="selectedItems1" value="val1" />Tax 10%
<br/>
<input type="text" id="output" value="Output" />
</form>
Everything is good in jsfiddle, its just you are doing wrong calculation in it. I'm assuming you want to find 10% of number you write in textfield.
If yes, the here you're doing it wrong
result = a + b;
Just replace above line with this in your fiddle and it'll work.
result = b;
This:
a = (result * 5000);
b = result * 0.1;
result = a + b;
should be:
a = (result * 5000);
b = a * 0.1; // calculate 10% of (result * 5000) not result
result = a + b;
or in one line like this:
result *= (5000 * 1.1);
Try using bodmas, brackets over division over multiplication over addition over subtraction.
results = (result * 5000) + result * 0.1;
Hello everyone I need you guys help with this
It's suppose to convert the value you entered after you choose an option and click convert.
HTML CODE:/(I'm not sure how to use drop down menus with java script)
<html>
<body>
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1" >Currency 1 to Currency2</option>
<option value="2" >Currency 2 to Currency1</option>
</select>
<br><br>
Value <input type="text" id="value"><br>
Conversion <input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
</body>
</html>
JAVASCRIPT CODE:
<script type="text/javascript">
function Conversion()
{
var val = document.getElementById ("value").value;
var madeSelection = document.getElementById ("Selection").value;
if(madeSelection==1( var ans= +value * 1.37); )){
if(madeSelection==2 ( var ans= +value * 1.30; )){
}
}
conversion.value = ans;
}
</script>
There are several problems that are causing this to be non-functional:
You declare a variable called val that you are not using. Everywhere else in your code, it is called value.
var val = document.getElementById ("value").value;
Older browsers may not deal with a value property of a select element
var madeSelection = document.getElementById ("Selection").value;
Your if statements are malformed (and nested for some reason), and some of the operations are weird.
if(madeSelection==1( var ans= +value( 0.37); )){
if(madeSelection==2 ( var ans= +value * 0.30; )){
...
When properly formatted, your code is:
if (madeSelection == 1(var ans = +value(0.37);)) {
if (madeSelection == 2(var ans = +value * 0.30;)) {
if (madeSelection == 3(var ans = +value * 2.70;)) {
if (madeSelection == 4(var ans = +value * 0.80;)) {
if (madeSelection == 5(var ans = +value * 3.38;)) {
if (madeSelection == 6(var ans = +value * 1.25;)) {}
}
}
}
}
}
When more properly written, it should be:
if (madeSelection == 1) {
var ans = +value(0.37);
}
if (madeSelection == 2) {
var ans = +value * 0.30;
}
if (madeSelection == 3) {
var ans = +value * 2.70;
}
if (madeSelection == 4) {
var ans = +value * 0.80;
}
if (madeSelection == 5) {
var ans = +value * 3.38;
}
if (madeSelection == 6) {
var ans = +value * 1.25;
}
although:
the ans variable, along with all of your other variables should be declared at the top of the function (because that's where they're actually declared anyway, look up variable hoisting).
I'm not sure why you're prefixing the righthand assigment with the +.
value is not a function, but you're apparently attempting to use it as one if madeSelection == 1.
Finally, you're referencing a variable called conversion which has not been defined. This will still probably work as you have an input with an id of conversion and most (but not all) browsers will store the id as a global variable pointing to the element.
Also, when you have many if statements, you may wan't to consider using a switch statement instead.
All together, it should look more like this:
function Conversion() {
var value = document.getElementById("value").value,
conversion = document.getElementById("conversion"),
madeSelection = document.getElementById("Selection"), // get the select
selection = madeSelection.options[madeSelection.selectedIndex].value, // get the selected option
ans = 0;
value = parseFloat(value);
if (!isNaN(value)) {
switch (selection) {
case "6":
ans = value * 1.25;
break;
case "5":
ans = value * 3.38;
break;
case "4":
ans = value * 0.8;
break;
case "3":
ans = value * 2.7;
break;
case "2":
ans = value * 0.3;
break;
case "1":
ans = value * 0.37;
break;
default:
ans = 0;
break;
}
}
conversion.value = ans;
}
<select name="converts" id="Selection">
<option>Choose Option</option>
<option value="1" >EC to US</option>
<option value="2" >EC to Euro</option>
<option value="3" >US to EC</option>
<option value="4" >US to Euro</option>
<option value="5" >Euro to EC</option>
<option value="6" >Euro to US</option>
</select>
<br />
<label for="value">Value</label>
<input type="text" id="value"><br>
<label for="conversion">Conversion</label>
<input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
This should work for you:
function Conversion() {
var val = document.getElementById("value").value,
madeSelection = document.getElementById("Selection").value,
ans
if (madeSelection == 1) ans = val * 0.37;
if (madeSelection == 2) ans = val * 0.30;
if (madeSelection == 3) ans = val * 2.70;
if (madeSelection == 4) ans = val * 0.80;
if (madeSelection == 5) ans = val * 3.38;
if (madeSelection == 6) ans = val * 1.25;
document.getElementById("conversion").value = ans;
}
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1">EC to US</option>
<option value="2">EC to Euro</option>
<option value="3">US to EC</option>
<option value="4">US to Euro</option>
<option value="5">Euro to EC</option>
<option value="6">Euro to US</option>
</select>
<br>
<br>Value
<input type="text" id="value">
<br>Conversion
<input type="text" id="conversion">
<br>
<br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
Instead a lot IF statements you should use SWITCH.
This is the right way
JS
function Conversion()
{
var val = parseInt(document.getElementById ("value").value);
var madeSelection = parseInt(document.getElementById ("Selection").value);
switch(madeSelection)
{
case 1:
var converted = val * 0.37; //EC to US
break;
case 2:
var converted = val * 0.30; //EC to EUR
break;
case 3:
var converted = val * 2.70; //US to EC
break;
//ETC....
default:
alert('You chose wrong option'); // if user chose wrong option, send him message
break;
}
document.getElementById ("conversion").value = converted;
return false; //prevent for submit form
}
Here is fiddle : http://jsfiddle.net/1cdkvpms/
I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}