Search code examples
javascriptarraysobjectinput

why input value doesn't change while function fires


I am coding a unit converter and its job is to convert a given amount of seconds to what ever unit the user whichs. the convertion system works perfectly but here comes the problem: the value of input doesn't change as user type their number in it. I don't see what the problem is.

HTML:

<body>
    <select class="select">
        <option value="second">second</option>
        <option value="minute">minute</option>
        <option value="hour">hour</option>
        <option value="day">day</option>
    </select>
    <input class="inp" type="text">
    <p class="p"></p>
    <script src="Untitled-1.js"></script>
</body>

JS:

let select = document.querySelector(".select")
let userAmountInput = document.querySelector(".inp")
let p = document.querySelector(".p")

let array = [
    {
    name:"second",
    second: userAmountInput.value * 1,
    minute: userAmountInput.value / 60,
    hour: userAmountInput.value / 3600,
    day: userAmountInput.value / 86400,
},
            ]

function updateP(e) {
    if (e.key == "Enter") {
        let x = select.value
        p.innerHTML = array[0][x]
        console.log(array[0][x])
    }
}
userAmountInput.addEventListener("keyup",updateP)

Solution

    1. select.value doesn't hold the value, you should use the event: event.target.value

    2. The array makes no sense, lets change that:

      1. To an object containing functions
      2. Get the function for the selected type
      3. Call the function with the current input value

    let select = document.querySelector(".select")
    let userAmountInput = document.querySelector(".inp")
    let p = document.querySelector(".p")
    
    const converters = {
        second: (n) => n * 1,
        minute: (n) => n / 60,
        hour:   (n) => n / 3600,
        day:    (n) => n / 86400
    };
    
    function updateP(e) {
        if (e.key == "Enter") {
        
            if (!converters[select.value]) {
                console.error('No converter found for', select.value);
                return;
            }
            
            let x = +e.target.value;
            let y = converters[select.value];
            p.innerHTML = y(x);
        }
    }
    userAmountInput.addEventListener("keyup",updateP)
    <body>
        <select class="select">
            <option value="second">second</option>
            <option value="minute">minute</option>
            <option value="hour">hour</option>
            <option value="day">day</option>
        </select>
        <input class="inp" type="text">
        <p class="p"></p>
        <script src="Untitled-1.js"></script>
    </body>