Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using KeyUp, how do I get a value after the enter key is released?

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>
like image 433
Michael Kheong Avatar asked Nov 06 '22 21:11

Michael Kheong


1 Answers

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>
like image 116
Rory McCrossan Avatar answered Nov 15 '22 06:11

Rory McCrossan