Search code examples
javascriptif-statementgetelementbyidgetelementsbyclassname

Alternative Document Method


Summarize the problem.

  1. The goal of this program is to determine if the users integer is even or odd.
  2. I believe my code could be more concise.
  3. There is a logical error that states that the HTML Input Element is undefined.

Describe what you've tried.

  1. I changed the document.getElementById() to the .querySelector() and .getElementByClassName.

Code -

https://jsfiddle.net/pherami1/jfh3xq69/2/

const input = document.getElementById('textInput');<br>
const button = document.getElementById('submitButton');<br>
    
button.addEventListener('click', evenOrOdd);

function evenOrOdd () {
    let result;
    let even;
    let odd;
    
    if (input % 2) {
        result = even;
    } else {
        result = odd;
    }
    document.getElementById('para').textContent = input + " is an " + result + " number.";
}

Solution

  • There are a number of things that you need to change -

    First thing - If you want to get the value of input, use .value.

    Second - Declare the input inside the evenOrOdd function. If you don't do so, then the value of input will not be changed every time you click the button.

    Third - The output of .value is a string, but to find whether a number is even or odd, we need to convert the string to a number using Number().

    Fourth - When you check for a number to be even or odd, you change the value of the result variable to even or odd. even and odd are variables, not strings. So, whatever the value of result is, it is always going to be undefined since even and odd are undefined. Change the value of result to strings "even" or "odd".

    Fifth - When you check for even numbers, you do (input % 2). If the number is even, then (input % 2) will evaluate to 0. 0 means false. So, even if your number is even, you will get "odd". Change the if condition to (input % 2 == 0)

    All these changes are applied in the below snippet. Check the snippet's code -

    let button = document.getElementById('submitButton');
    button.addEventListener('click', evenOrOdd);
    
    function evenOrOdd () {
        //Declare the input inside the function and use .value to get the value and Number() to convert the string to number.
        let input = Number(document.getElementById('textInput').value);
        let result;
        
        //Change the condition
        if (input % 2 == 0) {
            result = "even";//Change to strings, not variables
        } else {
            result = "odd";
        }
        document.getElementById('para').textContent = input + " is an " + result + "number.";
    }
    <input type="number" id="textInput" />
    <button id="submitButton">Submit</button>
    <p id="para"></p>