jeudi 3 janvier 2019

Checking input type in JS

I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.

The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.

Is typeof the right solution to this problem? If it is, why is this code not working?

document.getElementById('temperature-form').addEventListener('submit', calculateResult);

function calculateResult(e) {
    e.preventDefault();
    const celsiusInput = document.getElementById('celsius');
    const fahrenheitInput = document.getElementById('fahrenheit');
    let resultOutput = document.getElementById('result');
    // validate input data type and calculate result  
    if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) { 
        resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
    } else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
        resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';  
    } else {
        errorMessage('Please add a number in one of these fields');
    } 
}

Many thanks!

Aucun commentaire:

Enregistrer un commentaire