Simple time and half calculator in JavaScript - javascript

I have made a simple time and half calculator in HTML and JavaScript, but for some reason, when I click the Calculate button, the P element does not show the result.
Here is my code:
http://codepen.io/chrissylvester10/pen/wJxder
html>
<head>
</head>
<body>
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>
</body>
</html>
var fare = document.getElementById("#fare").value;
function calculator() {
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
Please fork it because I need to see the changes.

First thing, you don't need the # in var fare = document.getElementById("#fare").value;.
It should be var fare = document.getElementById("fare").value;
That line of code should also be inside the function, so it will read the new value every time you change it, otherwise, it will just return 0.
Lastly, you want to parse the number so it isn't misread as a string.
function calculator() {
var fare = parseInt(document.getElementById("fare").value);
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
edit:
A much simpler way to do this would be
function calculator() {
document.getElementById("result").innerHTML = document.getElementById("fare").value*1.5;
}

You are getting the value at the start and not the actual value.
Solution: Move the fare declaration inside of the function.
Small change: Get only fare as id.
function calculator() {
var fare = +document.getElementById("fare").value,
result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>

What about to enclose your Javascript into <script> tags?
And remove # from fare.

Related

Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How to convert Javascript numbers to a string and pass it to an input box

i'm stuck trying to convert feet to miles. here is my code so far:
function convertData() {
var distance = document.getElementById('distance').innerHTML;
var mile = 5280;
var result = distance /mile;
document.getElementById('distance').innerHTML = result;
};
and from the answer here, i'm trying to implement this to the
document.getElementById tag up in the beginning of the document found here..
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
..so when a user clicks that button, the data gets converted.
this is the default line when a user opens a page on first try:
any advice or thoughts?
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('answer').innerHTML = +result;
};
<div id="answer"></div>
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
I will recommend displaying the answer in another element, and leaving the input free for the user to make changes.
the simpliest way
html inputs with a type=number have the valueAsNumber property to directly process their numeric value.
(There is also a valueAsDate for those of type=date)
const
distance_el = document.getElementById('distance')
, mile = 5280
;
function convertData()
{
distance_el.valueAsNumber /= mile
}
<input type="button" value="Convert to Miles" onclick="convertData();">
<input id="distance" type="number" value="453454">
You should be getting/setting the input value property rather than the innerHTML.
The innerHTML property is used to return the HTML content of an element, while the value property is used to return the value of a text field.
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('distance').value = result;
};
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
Simplified version:
function convertData(t) {
t.nextElementSibling.value = t.nextElementSibling.value/5280;
};
<input type="button" value='Convert to Miles' onclick="convertData(this);">
<input id="distance" type="number" value=453454>

How to get a <input> id number into a var (Math)

I got a input number into a var. I subtracted it to a number.
Thank you vicodin for helping me! I fixed it and it works! (I changed names for my program)
<!DOCTYPE html>
<html>
<body>
<p></p>
<span><input type="number" id="guess1"><p id="g1s"></p></span>
<input type="button" onclick="Calculate()" value="Calculate">
<script>
function Calculate() {
var GuessCon1 = document.getElementById("guess1").value;
var GuessCon1sub = GuessCon1 - 500;
document.getElementById("g1s").innerHTML = GuessCon1sub;
}
</script>
</body>
</html>
You assigned a string "numb1" to variable g. If you want to get the value of the input, you need to find that element (e.g. with document.geElementById method) and take a value from it.
Also, you want to trigger calculation, for example by a button click. I added a code in a snippet, you can run it and play around with it to get the idea.
var button = document.getElementById("substract")
button.onclick = function() {
var g = document.getElementById("numb1").value
var a = 578;
var x = g - a;
document.getElementById("demo").innerHTML = x;
}
<input type="number" id="numb1">
<input type="submit" id="substract">
<p id="demo"></p>
Related links:
Input Text value Property
onclick event

Arithmetic expressions in Javascript

I have studied java and php for many years and recently just started developing in JavaScript as well. Anyway a fairly noob question but can anyone work out why this application isn't showing displaying the interest when the button is clicked? I have been using w3schools website to learn from.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Interest Calculator</title>
</head>
<body>
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
</body>
</html>
Many thanks,
Adam
You need to explicitly specify *. It is not normal for 5(3) = 15 in JavaScript or any programming language. You need to explicitly specify 5*(3):
var sum = amount*(1+rate)^years;
Working Code
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount*(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
Fiddle: http://jsbin.com/lovevazaxe
The OP uses the ^ operator and presumably wants to use the power-of operator.
In javascript the ^ operator refers to bitwise XOR - I don't think that's what the OP wants.
Instead, the power-of operation is done with the Math.pow() function.
So replace var sum = amount(1+rate)^years; with
var sum = Math.pow(amount*(1+rate),years)

Categories

Resources