I want to convert, with Select menu. So the first input box will read what temperature to convert from Select Menu, But it didn't work. When I select menu Celsius so the input will read the temperature as Celsius.
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f"></p>
You have multiple selector wrong in your Html as it has spaces on the ID's and in JavaScript selector you don't have space.
Just fix spaces in your elements ID's and it will work
e.g. "demo " != "demo"
Below is corrected ID's and JavaScript Selectors
function myFunction() {
if (document.getElementById("temperature").value == "Celcius") {
convertc();
} else {
convertf();
}
}
function convertc() {
var x;
document.getElementById("demo").innerHTML = " Degree Celcius ";
x = (document.getElementById("c").value - 32) * 5 / 9;
document.getElementById("f").value = Math.round(x);
}
function convertf() {
var x;
document.getElementById("demo").innerHTML = " Degree Fahrenheit ";
x = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(x);
}
<body>
<h2>JavaScript Celcius to Fahrenhet</h2>
<form>
<select id="temperature" onchange="myFunction()">
<option value="Celcius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="c"><span id="demo"> Degree </span></p>
<p>
<input id="f" ></p>
</body>
If you want to automatically select the first select option, you will need to trigger the event.
Note: For the trigger functionality, I reused logic from a previous answer of mine.
I also converted the calculations to lambda constants for brevity, see below.
const FAHRENHEIT_TO_CELSIUS = (value) => (value - 32) * 5 / 9;
const CELSIUS_TO_FAHRENHEIT = (value) => value * 9 / 5 + 32;
// ==============================================================
var comboEl = document.getElementById('temperature');
addEventListener(comboEl, 'change', onComboChange); // Add an event listener.
triggerEvent(comboEl, 'change', {}); // Automatically trigger the event.
// ==============================================================
function onComboChange(e) {
var inputValue = document.getElementById('input-degrees').value;
if (e.target.value === 'Celsius') {
updateDisplay('Celsius', CELSIUS_TO_FAHRENHEIT(inputValue));
} else {
updateDisplay('Fahrenheit', FAHRENHEIT_TO_CELSIUS(inputValue));
}
}
function updateDisplay(label, value) {
document.getElementById('degrees-label').innerHTML = 'Degrees ' + label;
document.getElementById('output-degrees').value = Math.round(value);
}
// ==============================================================
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function() {
handler.call(el);
});
}
}
function triggerEvent(el, eventName, options) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(eventName, options);
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, true, true, options);
}
el.dispatchEvent(event);
}
<h2>JavaScript Celsius to Fahrenheit</h2>
<form>
<select id="temperature">
<option value="Celsius">Celcius</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</form>
<p>
<input id="input-degrees" value="0" />
<span id="degrees-label">Degrees</span>
</p>
<p><input id="output-degrees" /></p>
Related
I am having an issue with an event listener on a select and a value not updating but cannot figure out what the issue.
Code is below. Basically need the price field to update based on the function above it. Unfortunately i cannot have them all in the same function and need to have them separate. The first console.log does show the value for y but the second does not show the value for price.
var factors = function factor(j) {
var mySelect = document.getElementById("mySelect").value;
if (mySelect == "car") {
lease = "166";
} else if (mySelect == "truck") {
lease = "200";
}
console.log("this is my lease value - " + lease);
return lease * j;
};
var monthlyprice = function monthlyprice() {
var price = factors(1);
console.log("this is my price -" + price);
};
var type = document.getElementById("mySelect");
type.addEventListener("click", factors);
<form action="">
<label for="mySelect">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
since monthlyprice calls factor() you want to place the listener on monthlyprice
var type = document.getElementById("mySelect");
type.addEventListener("change", monthlyprice);
function monthlyprice() {
var price = factor(1)
console.log("this is my price =" + price);
};
function factor(j) {
var y;
var z = document.getElementById("mySelect").value;
if (z == "car") {
y = "166";
} else if (z == "truck") {
y = "200";
}
console.log("this is my y value - " + y);
return y * j;
};
<form action="">
<label id="label">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
I have created a conversion table which converts miles to kilometres and kilometres to miles depending on whichever one the user chooses. They input two numbers which indicates the two ranges so if they input 2 and 5 and choose km to m it will then show 2km to 5km converted to miles. However, what I am trying to do is if the user inputs a greater number to start with for instance if you enter 10 and 2 it should still do the same but rather it should go from 10km down to 2km so in descending order, so I know it will be something along the lines of if(rangeStart>rangeEnd){i--;}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function conversion(n) {
if (document.getElementById('mtokm').checked) {
return (n/0.62137).toFixed(2);
}
else {
return (n*0.62137).toFixed(2);
}
}
function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio() && rangeStart != false && rangeEnd != false) {
divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";}
for(i=rangeStart;i<=rangeEnd;i++) {
if(i%2==0)
{
divStr+= "<tr bgcolor=\"yellow\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
else
{
divStr+= "<tr bgcolor=\"green\"><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
}
}
document.getElementById("divResult").innerHTML=divStr;
}
else
{
alert("Please make sure you have entered an integer in both text boxes");
}
}
function getnputValue(input) {
var nn = $("input[name=convert]:checked").val()
var myInt = document.getElementById(input).value;
if(myInt == parseInt(myInt))
return parseInt(myInt);
else
return false;
}
function check() {
var radios = document.getElementsByName("choice");
$("input[name=convert]:checked").val()
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
return true;
}
}
return false;
}
function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
End : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/> Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/> Kilometre to Miles
<br>
<br>
<button onClick="conversionTable(getnputValue('rangeTxt'), getnputValue('rangeTxt2'))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
Check whether the end is higher or lower than the start. Then set variables that are used to control the for loop.
var increment, compare;
if (rangeStart <= rangeEnd) {
increment = 1;
compare = function(x, y) {
return x <= y;
};
} else {
increment = -1;
compare = function(x, y) {
return x >= y;
};
}
for (i = rangeStart; compare(i, rangeEnd); i += increment) {
// display code
}
I'm making a basic usd converter for practice in html/javascript.
However when I select the euro option it does the same as for the peso option.
<html>
<head>
<title>Currency Converter</title>
<style>
</style>
</head>
<body>
<input id="amount"> </input>
<p>usd Contverted to</p>
<p class="output"> </p>
<select id="select"> <option value="1">Peso's</option> <option value="2">Euro's</option> </select>
<p id="answer"> is </p>
<input type="submit" value="Submit" onclick="run()">
<script>
function run() {
var Amount = document.getElementById("amount").value;
if (select = 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select = 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
</script>
</body>
</html>
You are not comparing select,you are setting it.
if (select == 1) {
document.getElementById("answer").innerHTML = ...
} else if (select == 2) {
= -> setting a value
== -> comparing
it should be select == 1
select=1 will always return true, because this way you are simply assigning a value, not checking for equality
You are not getting value of select
You are not comparing select value in if condition, make it as select == 1 and select == 2
Complete solution here
Change your javaScript function as below
function run() {
var Amount=document.getElementById("amount").value;
var select=document.getElementById("select").value;
if (select == 1) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 16.39 + " =-=-=";
} else if (select == 2) {
document.getElementById("answer").innerHTML = "=-=-= " + Amount * 0.9 + " =-=-=";
} else {
}
}
Multiplying 'Area' value with one of three separate fixed values (types of paint:Premium/Luxury/Regular) so as to calculate the total.
There are three values to choose from the dropdown option, but the calculator function always loads the last value as the multiplier.
Calculator works with one fixed value only
window.onload = function(){
function findID(id) { //function to make 'getElementById easier to maintain;
return document.getElementById(id);
}
var calculator = {
multOne: findID('mult-one'),
multTwo: findID('mult-two'),
multThree: findID('mult-three'),
multFour: findID('mult-four'),
product: findID('product'),
calculate: findID('calculate'),
clear: findID('clear')
};
// Onclick Events for buttons
calculator.clear.onclick = function() {
calculator.multOne.value = '';
calculator.multTwo.value = '';
calculator.multThree.value = '';
calculator.multFour.value = '';
calculator.product.value = 'Please Refresh your browser';
console.log(result = 0);
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multTwo.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multThree.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
calculator.calculate.onclick = function() {
var result = calculator.multOne.value * calculator.multFour.value;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
}
<form method="post">
<p class="home-widget-caption" style="color:#ff4102; font-size:14px;">Type of Paint</p>
<select name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
<br>
<p class="home-widget-caption" style="color:#ff4102; font-size:14px; margin-top:10px;">Painting Area</p>
<input type="text" id="mult-one" style="width:120px"> <span style="color:#999999">sq.ft.</span>
<br><br>
<div style="text-align:center">
<button type="button" id="calculate" style="padding:10px 30px 10px 30px; margin-bottom:15px">Calculate My painting cost</button>
<button type="button" id="clear" style="display:none">Clear</button>
</div>
<p class="home-widget-caption" style="color:#ff4102; font-size:16px">Your total expenditure</p>
<input type="text" id="product" style="width:270px">
<br><br>
</form>
You are not supposed to have multiple
calculator.calculate.onclick = function() {}
You must have only one, where you get the selected value of your <select>, and do the calculations.
Your <select> could have an id you would use later to get selected option value :
<select id="typesID" name="types" style="width:120px">
<option id="mult-two" value="30">Luxury</option>
<option id="mult-three" value="20">Premium</option>
<option id="mult-four" value="10">Regular</option>
</select>
Then in your JS side :
calculator.calculate.onclick = function() {
var e = document.getElementById("typesID");
var selectedValue = e.options[e.selectedIndex].value;
var result = calculator.multOne.value * selectedValue;
console.log(result);
if(isNaN(result)) {
calculator.product.value = 'Not Valid - Try Again!!'
}
else {
calculator.product.value = result;
}
}
I am new to coding (trying to learn) and I cant figure out how to get the var of the check box value outside of the function.
Javascript:
$(document).ready(function() {
var quantity= parseInt($('#phones').val());
$("#check1 input:checkbox").change(function() {
var feature = 0;
$("#check1 input:checkbox").each(function() {
if ($(this).is(':checked')) {
feature += parseInt($(this).prop('value'));
}
});
});
var grand = feature * (quantity * Number ('0.1'))
var total = quantity + grand
});
HTML:
<input id="phones" type="numerical" value="0" style="text-align: right"/>
<div id="check1">
<input type="checkbox" value="1" />
function getResult(feature, phones) {
if (feature <= 0 || phones <= 0) {
return 'Error...., enter the number of phones and check some checkbox';
}
return (feature * (+phones * 0.1)) + +phones;
}
function getFeature() {
var feature = 0;
$('#check1 input:checkbox:checked').each(function () {
feature += +$(this).prop('value') || 1;
});
return feature;
}
$(document).ready(function() {
var $phones = $('#phones'),
$result = $('#result');
$("#check1 input:checkbox").change(function() {
$result.html(getResult(getFeature(), $phones.val()));
});
$("#phones").keyup(function() {
$result.html(getResult(getFeature(), $phones.val()));
});
});
Demo: http://jsbin.com/hivilu/2/