'Multiplying in javascript with textbox

I am a beginner javascript programmer. I made a very simple program to multiply 2 numbers with textbox. At first it worked. But then I wrote some logic to avoid some bugs. And some of the logics are not working. could anybody take a look at this code and tell me what's wrong here:

let text1;
let text2;
let ans;

// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
    text1=document.getElementById('text1').value;
    text1 = Number(text1);
    text2=document.getElementById('text2').value;
    text2 = Number(text2);

    // checking if it is a number or not
    if(isNaN(text1)||isNaN(text2)){
        document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
    }

    // checking if it is an integer or not. 
    else if(text1.length>0 && Number.isInteger(text1)==false && text2.length>0 && Number.isInteger(text2)==false){
        document.getElementById('P').innerHTML='You cant multiply with decimal points';        
    }

    // checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
    else if(text1.length==0||text2.length==0){
        document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
    // else,  if it has no problem just multiply.
    else{
        let ans=BigInt(text1*text2);
        document.getElementById('P').innerHTML=ans;
        document.getElementById('zero').innerHTML='&times';
    }
}

I am getting the correct output when i enter the integer values in the text box and click submit button. But the problem is both the else if statement is not working. when i give the input as a float value it is not doing anything. It has to display the message , but it is not. same when i dont give any input and click the submit button. It is not displaying the message. Why does this happen. How to solve this?

HTML of this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>calculator</title>
    <link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
    <input type="text" id="text1" placeholder="enter a value"> 
    <p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
    <br><br><br><p id="P"></p>
    <br><br><br><br><br><button id="mul">Multiply</button>
    <br><br><br><br><br><button id="sub">Subtract</button>
    <br><br><br><br><br><button id="div">Divide</button>
    <br><br><br><br><br><button id="add">Add</button>
    <script src="calculator.js"></script>
</body>
</html>


Solution 1:[1]

You used double equal signs and not triple. in order to check for strict equality.

now it works:

let text1;
let text2;
let ans;

// returning the value inside the texbox.
document.getElementById('mul').onclick = () => {
  text1 = document.getElementById('text1').value;
  text1 = Number(text1);
  text2 = document.getElementById('text2').value;
  text2 = Number(text2);

  // checking if it is a number or not
  if (isNaN(text1) || isNaN(text2)) {
    document.getElementById('P').innerText = 'it should be a number. Not alphabets or symbols';
  }

  // checking if it is an integer or not. 
  else if (!(text1.length > 0 && Number.isInteger(text1)) && !(text2.length > 0 && Number.isInteger(text2))) {
    document.getElementById('P').innerHTML = 'You cant multiply with decimal points';
  }

  // checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
  else if (text1.length === 0 || text2.length === 0) {
    document.getElementById('P').innerHTML = 'you cant do any calculations with blank textbox';
  }
  // else,  if it has no problem just multiply.
  else {
    let ans = BigInt(text1 * text2);
    document.getElementById('P').innerHTML = ans;
    document.getElementById('zero').innerHTML = '&times';
  }
}
<input type="text" id="text1" placeholder="enter a value"> 
    <p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
    <br><br><br><p id="P"></p>
    <br><br><br><br><br><button id="mul">Multiply</button>
    <br><br><br><br><br><button id="sub">Subtract</button>
    <br><br><br><br><br><button id="div">Divide</button>
    <br><br><br><br><br><button id="add">Add</button>
    <script src="calculator.js"></script>

Solution 2:[2]

This should work. There is no length property available in Number. So if you cast your inputs to Number, inputValue.length will no longer work.

let text1;
let text2;
let ans;

// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
    text1=document.getElementById('text1').value;
    text1 = Number(text1);
    text2=document.getElementById('text2').value;
    text2 = Number(text2);

    // checking if it is a number or not
    if(isNaN(text1)||isNaN(text2)){
        document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
    }

    // checking if it is an integer or not. 
    else if(!Number.isInteger(text1) || !Number.isInteger(text2)){
        document.getElementById('P').innerHTML='You cant multiply with decimal points';        
    }

    // checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
    else if(!text1.length||!text2.length){
        document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
    // else,  if it has no problem just multiply.
    else{
        let ans=text1*text2;
        document.getElementById('P').innerHTML=ans;
        document.getElementById('zero').innerHTML='&times';
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>calculator</title>
    <link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
    <input type="text" id="text1" placeholder="enter a value"> 
    <p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
    <br><br><br><p id="P"></p>
    <br><br><br><br><br><button id="mul">Multiply</button>
    <br><br><br><br><br><button id="sub">Subtract</button>
    <br><br><br><br><br><button id="div">Divide</button>
    <br><br><br><br><br><button id="add">Add</button>
    <script src="calculator.js"></script>
</body>
</html>

Solution 3:[3]

let text1, text2;

// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
    text1=parseInt(document.getElementById('text1').value)
    text2=parseInt(document.getElementById('text2').value)

    // checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
    if(text1.length==0){
        document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
    }

    // else,  if it has no problem just multiply.
    else{
        document.getElementById('P').innerHTML=text1*text2;
        document.getElementById('zero').innerHTML='&times';
    }
}
<html lang="en"><head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>calculator</title>
    <link rel="stylesheet" href="calculator.css">
</head>
<body style="text-align: center;">
    <input type="number" min="0" id="text1" placeholder="enter a value"> 
    <p id="zero"></p><input type="number" min="0" placeholder="enter a value" id="text2">
    <br><br><br><p id="P"></p>
    <br><br><br><br><br><button id="mul">Multiply</button>
    <br><br><br><br><br><button id="sub">Subtract</button>
    <br><br><br><br><br><button id="div">Divide</button>
    <br><br><br><br><br><button id="add">Add</button>
    <script src="calculator.js"></script>
</html>

Explaining code:

First, I rewrite all input types to number, so now user can't write any symbols except numbers, and I'm removed isNaN check because of reason I said before. Also, I used only text1 and text2 variables and removed ans variable because calculating is doing right before writing calculated number in innerHTML. Plus numbers automatically parsed as integers, so I removed integer check.

Solution 4:[4]

Here's your app working 100%.

The reason your code wasn't working because there is no length property on a number type. length is only on arrays and strings.

Some issues with your code:

  1. text1 and text2 shouldn't be let variables at the top of the global scope. They should be pointers to their respective DOM nodes, which .value can be used on at any time.
  2. Instead of using Element.onclick, use Element.addEventListener('click', callback) instead.
  3. Avoid using innerHTML. Is is best practice to use textContent or innerText (textContent is best).
  4. You can set an input element's type to be number, which will prevent the user from ever even entering a non-number value.
  5. When you have a ton of else if statements, it's better syntactically to use a switch case (some might argue against this, but in my opinion it's much easier to read).
  6. I rarely see the <br> tag being used in modern web-applications. Use it sparingly, and opt for flex or grid instead to space out your items.
  7. Don't use the == operator, instead, use the "strict equals" operator: ===
  8. If you're checking for whether or not a condition is false, you don't have to do if (conditon === false). You can negate the condition with the ! operator: if (!condition). This will also fire if the condition returns a falsy value, such as '', 0, undefined, null, or NaN.

Most importantly, try to separate your logic into "Lego blocks". Basically, make small functions that do one thing. Debugging mega functions is not fun. We've implemented this functional logic in the example below by creating the validate function.

const textbox1 = document.querySelector('#text1');
const textbox2 = document.querySelector('#text2');
const pTag = document.querySelector('#P');

const actions = {
    mul: 'mul',
    sub: 'sub',
    div: 'div',
    add: 'add',
};

const validate = (num1, num2) => {
    if (isNaN(num1) || isNaN(num2) || !Number.isInteger(num1 + num2)) return false;
    return true;
};

const handleClick = ({ target }) => {
    let answer;
    
    const val1 = +textbox1.value;
    const val2 = +textbox2.value;

    if (!validate(val1, val2)) {
        pTag.textContent = 'Invalid input! Much provide two integers.';
        return;
    }

    switch (target.getAttribute('id')) {
        case actions.add:
            answer = val1 + val2;
            break;
        case actions.sub:
            answer = val1 - val2;
            break;
        case actions.div:
            answer = val1 / val2;
            break;
        case actions.mul:
            answer = val1 * val2;
    }

    pTag.textContent = answer;
};

window.addEventListener('DOMContentLoaded', () => {
    for (const action of Object.values(actions)) {
        const elem = document.querySelector(`#${action}`);
        elem.addEventListener('click', handleClick);
    }
});
<body>
    <input type="number" id="text1" placeholder="enter a value" />
    <p id="zero"></p>
    <input type="number" placeholder="enter a value" id="text2" />
    <p id="P" style="color: red"></p>
    <div style="display: flex; flex-direction: column; gap: 20px; max-width: 200px">
        <button id="mul">Multiply</button>
        <button id="sub">Subtract</button>
        <button id="div">Divide</button>
        <button id="add">Add</button>
    </div>
</body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guy Nachshon
Solution 2 emkarachchi
Solution 3
Solution 4 mstephen19