I am trying to create a keyup event handler that checks the first text box so that when enter is released, it calculates the number hours worked by the user input. If the user enters a number LESS THAN 40 it takes that input and multiplies it by $12, but if the user enters a number more than 40 (hours), it takes the extra hours and multiplies it by $18 and add $480 ($12 x 40 hours) and returns a value in the second text box. I believe I am just using the wrong operator or the wrong method used to get keyup for the enter key. Thanks in advance
let hours = document.getElementById("box1")
let pay = document.getElementById("box2")
document.addEventListener("keyup", press);
function press() {
if (event.key === "Enter") {
let a = hours.value;
if hours.value <= 40;
let b = (a * 12);
else hours.value >= 40;
let c = [((a - 40) * 18) + 480]
let c = pay.value = b;
}
<p>Enter your hours:</p> <input type="number" id="box1">
<p>Your pay will appear here:</p> <input type="text" id="box2" disabled>
Your JS has several syntax problems, such as mismatched braces, semi-colons in the wrong place and not receiving the event as an argument in to the press()
function.
The logic itself can be broken down in to two stages, one to work out the base earnings and one to work out earnings past the 40 hour level. Also note that you need to be wary of invalid values being entered in to the field as, although it's a number field, it will still accept some alphabetic characters, such as e
. To work around that make sure to parseInt()
any value you receive before working with it. Try this:
var hourBreak = 40;
var baseRate = 12;
var higherRateFactor = 1.5;
let hourField = document.getElementById("box1")
let payField = document.getElementById("box2")
document.addEventListener('keyup', press);
function press(e) {
if (e.keyCode === 13) {
var hours = parseInt(hourField.value, 10) || 0;
var baseEarnings = Math.min(hours, hourBreak) * baseRate;
var higherEarnings = Math.max(hours - hourBreak, 0) * (baseRate * higherRateFactor)
payField.value = baseEarnings + higherEarnings;
}
}
<p>Enter your hours:</p> <input type="number" id="box1">
<p>Your pay will appear here:</p> <input type="text" id="box2" disabled>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With