Javascript If statement with boolean value - javascript

I have two dropdown select boxes and I want a textbox to update with a value based on the selected texts from the two boxes.
If the first box selected is 'dollars' and the second is 'naira', I want the rate to be 100 and this value inputted in the textbox with the id of rate.
Unfortunately when my function executes I keep getting a value of undefined. Something is obviously wrong with my if statement but I can't figure it out.I need to do this with pure javascript, not jquery.
Here is my code:
<p>Select currency to send</p>
<select id="fromCurrency">
<option value = "Dollars">Dollars</option>
<option value = "Pounds">Pounds</option>
<option value = "Naira">Naira</option>
</select>
<p>Select currency to receive</p>
<select id="toCurrency">
<option value = "Naira">Naira</option>
<option value = "Dollars">Dollars</option>
<option value = "Pounds">Pounds</option>
</select><br />
<label>Enter amount to send</label>
<input type="text" id="amount" name="amount"><br />
<button onclick ="getRate()">Get Rate</button><br />
<label>Rate:</label>
<input type="text" id="rate" name="rate"><br />
<label>Total:</label>
<input type="text" id="total" name="total"><br />
<script>
function getRate() {
var e = document.getElementById("fromCurrency");
var eSend = e.options[e.selectedIndex].value;
var i = document.getElementById('toCurrency');
var eReceive = i.options[i.selectedIndex].value;
var rate = document.getElementById('rate');
var dollars = {
'pounds':20,
'naira':15
};
if (eSend =='dollars' && eReceive =='naira') {
var rValue= (dollars['pounds']);
};
rate.value = rValue;
};
</script>
Please advice.
Thanks
EDIT:
I tried to use a switch statement as I have about 6 different conditions, and this is what I tried but it didn't work.
var rValue = 0;
switch (rValue) {
case (eSend =='Dollars' && eReceive =='Naira'):
rValue= (dollars['naira']);
break;
case (eSend =='Dollars' && eReceive =='Pounds'):
rValue= (dollars['pounds']);
break;
}
rate.value = rValue;

JavaScript is case-sensitive, your if statement:
if (eSend =='dollars' && eReceive =='naira') {
is looking for dollars, not Dollars, capitalize to match your select values:
if (eSend =='Dollars' && eReceive =='Naira') {

Related

How to find average of innerHTMLs?

I have input fields and selects. For different select options there are different equations. After calculating equations, I used .innerHTML to show results. I got first part of the code worked, but I am stuck at the last part. When I try to calculate average of outputs, It shows Nan. Can anyone help with this problem? Thanks in advance.
var container = document.getElementById('container');
var span1 = document.getElementById('span1');
var span2 = document.getElementById('span2');
var output = document.getElementById('output');
function average() {
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseFloat(document.getElementById('d').value);
if (document.getElementById('select1').value == '1') {
span1.innerHTML = ((a+b)/(a*b)).toFixed(2);
} else if (document.getElementById('select1').value == '2') {
span1.innerHTML = ((a*b)/(a+b)).toFixed(2)
} else {
span1.innerHTML = '';
}
if (isNaN(span1.innerHTML)) {
span1.innerHTML = '';
}
if (document.getElementById('select1').value == 'none1') {
span1.innerHTML = 'None'
}
if (document.getElementById('select2').value == '3') {
span2.innerHTML = ((c+d)*100/(c*d)).toFixed(2);
} else if (document.getElementById('select2').value == '4') {
span2.innerHTML = ((c*d)*100/(c+d)).toFixed(2)
} else {
span2.innerHTML = '';
}
if (isNaN(span2.innerHTML)) {
span2.innerHTML = '';
}
if (document.getElementById('select2').value == 'none2') {
span2.innerHTML = 'None'
}
var percent = document.getElementsByClassName('percent');
for (var i = 0; percent.length > i; i++) {
if (percent.length > 0) {
output.innerHTML = percent[i]/(percent.length);
}
}
}
container.addEventListener('change', average);
container.addEventListener('input', average);
<div id="container">
<input id="a" type="number">
<input id="b" type="number">
<select name="abc" id="select1">
<option value="Choose">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="none1">None</option>
</select>
<br>
<input id="c" type="number">
<input id="d" type="number">
<select name="abcd" id="select2">
<option value="Choose">Choose...</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="none2">None</option>
</select>
<span id="span1" class="percent"></span>
<span id="span2" class="percent"></span><br>
<span id="output"></span>
</div>
.innerHTML gets or sets the content of an element by invoking the HTML parser on the string passed as the value or extracted from the element. When the content is, or is to become just text (no HTML to be parsed), you should use .textContent as this will not invoke the HTML parser on the content, which saves processing power. In your case, you should be using .textContent.
Now, either way, data sent to or gotten from either .innerHTML or .textContent is a string, so if you want to do math with the value, you need to first convert it to a number. This can be done in several ways:
parseInt(stringToBeConverted, radix)
parseFloat(stringToBeConverted)
Number(stringToBeConverted)
+stringToBeConverted
Now, you have two issues, first when some of the text fields are still empty, their value is an empty string and parseFloat() on an empty string returns NaN. This can be solved by giving each field a default value of 0 in the HTML (i.e. <input id="a" type="number" value="0">).
Second, even with a, b, c, and d all having numeric values, your math:
((a + b) / (a * b)).toFixed(2);
Will result in NaN when a * b results in 0 because that will result in a division by zero situation.
You need to change your algorithm to test for this situation before doing the math.
I have no idea what you're trying to do, but I think this might be the correct solution it's a working way of getting the value of the percent[i] HTML element:
Change
output.innerHTML = percent[i]/(percent.length);
to
output.innerHTML = percent.item(i).innerHTML/(percent.length);
or
output.innerHTML = percent[i].innerHTML/(percent.length);

JavaScript check for input only works backwards

When I fill in all the input fields and choose an option in the select dropdown, for some reason the class will not be removed unless I start with the select dropdown. How come is that? I really don't get it.
var firstNameInput = document.getElementById('first_name_input');
var lastNameInput = document.getElementById('last_name_input');
var emailInput = document.getElementById('email_input');
var jobTitleInput = document.getElementById('job_title_input');
var departmentSelect = document.getElementById('department_select');
function checkForInput() {
var inputFields = firstNameInput.value && lastNameInput.value && emailInput.value && jobTitleInput.value && departmentSelect.options[departmentSelect.selectedIndex].value;
if(inputFields != '') {
copyButton.classList.remove('disabled');
} else {
copyButton.classList.add('disabled');
}
}
<form>
<input id="first_name_input" type="text" onkeyup="checkForInput();">
<input id="last_name_input" type="text" onkeyup="checkForInput();">
<input id="email_input" type="email" onkeyup="checkForInput();">
<input id="job_title_input" type="text" onkeyup="checkForInput();">
<select id="department_select" onchange="checkForInput();">
<option value="" disabled selected>Afdeling</option>
<option value="administration">Administration</option>
<option value="marketing">Marketing</option>
<option value="support">Support</option>
<option value="reklamation">Reklamation</option>
<option value="produktion">Produktion</option>
</select>
</form>
<a class="btn disabled" id="copyButton">Copy</a>
Here is a functional version:
<style>
.btn {
color: blue;
}
.disabled {
color: red;
font-size: 20px;
}
</style>
<form>
<input id="first_name_input" type="text" onkeyup="checkForInput();">
<input id="last_name_input" type="text" onkeyup="checkForInput();">
<input id="email_input" type="email" onkeyup="checkForInput();">
<input id="job_title_input" type="text" onkeyup="checkForInput();">
<select id="department_select" onchange="checkForInput();">
<option value="" disabled selected>Afdeling</option>
<option value="administration">Administration</option>
<option value="marketing">Marketing</option>
<option value="support">Support</option>
<option value="reklamation">Reklamation</option>
<option value="produktion">Produktion</option>
</select>
</form>
<a class="btn disabled" id="copyButton">Copy</a>
<script>
const checkForInput = () => {
// start a tally to see how many fields have values
let allDone = 0
// get value of each element
const firstNameInput = document.getElementById('first_name_input').value
const lastNameInput = document.getElementById('last_name_input').value
const emailInput = document.getElementById('email_input').value
const jobTitleInput = document.getElementById('job_title_input').value
const departmentSelect = document.getElementById('department_select').value
// put values into an array
const currentValues = [
firstNameInput,
lastNameInput,
emailInput,
jobTitleInput,
departmentSelect
]
// map over array and if value has any length, (1 character or greater)
// increment tally by 1
currentValues.map((value) => value.length ? allDone += 1 : false)
// if tally = 5, all fields have data in them, remove disabled class
if (allDone === 5) return copyButton.classList.remove('disabled')
// else add disabled class (just incase they wipe out a field)
return copyButton.classList.add('disabled')
}
</script>
I demonstrated several techniques that you can research further:
fat arrow syntax, http://wesbos.com/arrow-functions/
array literal, What is array literal notation in javascript and when should you use it?
Array.map, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
ternary operator, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
inline IF statement shorthand, you can omit { and } for if statements that only have one expression, such as if (something === 'ok') console.log(something)
I used that along with explicit returns to get rid of the else { } block
const and let, http://wesbos.com/let-vs-const/
implicit return, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
This code will be easy to extend and maintain if you need to add or remove fields.
Put a console.log(currentValues) right above currentValues.map() if you want to see how it is behaving on keypress.
If you want to see even more, change the map part to this:
currentValues.map((value) => {
console.log('Examining:', value)
console.log('Character length:', value.length)
console.log('Number of completed fields:', allDone)
return value.length ? allDone += 1 : false
})

Calculate the weight of planet on drop downs and print it to input type

I have the code for a form with some drop down menus with different options in it and I have also create alert pop up message so that they cannot select same planet now. I also have disable one input on one textbox for input because I only can put one input.
My question is how do I calculate the weight of the planet based on the dropdown box I selected? And also print/ display it on the input type means if I select earth and my input type (weight) is 60N, if my second select is Venus it will calculate the weight for me and print / display it to input type.
Below is roughly my HTML code and JavaScript code. I'm new to JavaScript.
html :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name="123" id="text1"
onchange="process_selection(this)" placeholder=""> N
</select>
<br>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<option value="0">Earth</option>
<option value="1">Venus</option>
<option value="2">Mars</option>
<option value="3">Jupiter</option>
<input type="text" name = "123" id="text2"
onchange="process_selection(this)" placeholder=""> N
</select>
javascript :
<script type="text/javascript">
function process_selection(obj)
{
var input1 = document.getElementById("select1").value;
var input2 = document.getElementById("select2").value;
var texta = document.getElementById("text1");
var textb = document.getElementById("text2");
if(input1 == input2)
{
alert("Please select other planet");
}
if(texta.value != "")
{
document.getElementById("text2").disabled = true ;
}
if(textb.value != "")
{
document.getElementById("text1").disabled = true ;
}
// var xx = input1.options[input1.selectedIndex].value;
var SurfaceGravityEarth = 1;
var SurfaceGravityVenus= 0.907;
var SurfaceGravityMars= 0.377;
var SurfaceGravityJupiter= 2.364;
var weight1 , weight2;
// var sg1;
// var sg2;
if (input1 == "0" )
{
weight1 = document.getElementById("text1") * SurfaceGravityEarth;
}
if (input2 == "1" )
{
weight2 = document.getElementById("text1") * SurfaceGravityVenus ;
document.getElementById("text2").value= weight2 ;
}
}
I'm stuck at the calculation part.
first, get the value of textbox and convert it to number type (integer, float etc).
Try the following code:
weight1 = parseInt(document.getElementById("text1").value) * SurfaceGravityEarth;
use parseInt() to convert to integer type.
if you want to convert to float type use parseFloat()
or you can simply use Number() method for both integer and floating point numbers

How to compare <option> “data-names” in an “if” statement?

I have a slight issue. I have options with a “value” and a “data-name”.
<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>
I want the computer return a specific value if the selected option is a certain “data-name”
Say there are 2 “data-names”, X and Y.
How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?
I’m thinking something along the lines of this:
var data_name1 = e.options[e.selectedIndex].dataset.name1;
if (data_name1 == “X”) {
…
}
else if (data_name == “Y”) {
…
}
else {
…
}
Is this possible?
Thanks!
Full code---
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
You need to use the == operator to compare objects.
= is an assignment expression.
if (data_name1 == “X”) {
// Operations if data_name is equal to X
}
else if (data_name == “Y”) {
// Operations is data_name is equal to Y
}
else {
}

Change label text using JQuery

I want the labels to change whenever the user changes from Metric to Imperial.
It correctly detects the change and stores the current value selected, steps into the if statement, but then nothing happens.
Here is my JavaScript.
$(document).ready(function()
{
$("select[name = unit]").change(function()
{
var selected = $("option:selected", this).text();
if(selected == "Metric (cm)")
{
$("label[for = unit]").text("mm");
}
else if(selected == "Imperial (inches)")
{
$("label[for = unit]").text("in");
}
});
})
And my html.
<form name ="Calculator">
Unit of Measurement:
<select name = "unit">
<option value = "120904000">
Metric (cm)
</option>
<option value = "4760000">
Imperial (inches)
</option>
</select>
<br>
Root Diameter: <input type = "text" name = "root" autocomplete = "off">
<label for = "unit"></label>
<br>
Width between bearings: <input type = "text" name = "bearings" autocomplete = "off">
<label for = "unit"></label>
<br>
End Fixity:
<select name = "fixity">
<option value = ".36">
1
</option>
<option value = "1.0">
2
</option>
<option value = "1.47">
3
</option>
<option value = "2.23">
4
</option>
</select>
<br>
Max Speed (RPM): <input type = "text" name = "speed" autocomplete = "off"><br>
Reset
Calculate
Exit
</form>
I cant really guess where u missing.But check this js fiddle where i used your code and its working absolutely fine for me .
Your code Fiddle
$("select[name = unit]").change(function()
{
var selected = $("option:selected", this).text().trim();
if(selected == "Metric (cm)")
{
$("label[for = unit]").text("mm");
}
else if(selected == "Imperial (inches)")
{
$("label[for = unit]").text("inches");
} });
I updated the jsfiddle for you .You needed to add this trim at the end like this :
var selected = $("option:selected", this).text().trim();
and you set to go.
Here is updated jsfiddle :
updated code fiddle

Categories