I jump directly to the Else

1

I have to enter two numbers and you have to tell me if they are even or odd. It is half done but I try it and I directly jump the alert of the else, regardless of whether the numbers are even or not.

<script type="text/javascript">
  function comprobar() {

    var num1 = document.getElementById("num1");
    var num2 = document.getElementById("num2");

    if (num1 % 2 == 0 && num2 % 2 == 0) {
      alert('par');
    } else {
      alert('impar');
    }
  }
</script>

<input type="text" id="num1">
<input type="text" id="num2">
<input type="button" id="boton" value="comprobar" onclick="comprobar()">
    
asked by Nacho rx 02.02.2018 в 14:49
source

4 answers

8

Your problem is that you are getting the element with id num1 and num2 but you are not taking its value, if not the element of the whole DOM, so you always jump to else . You need to make a .value of the item.

  function comprobar() {

    var num1 = document.getElementById("num1").value;
    var num2 = document.getElementById("num2").value;

    if (num1 % 2 == 0 && num2 % 2 == 0) {
      alert('par');
    } else {
      alert('impar');
    }
  }
<input type="text" id="num1">
<input type="text" id="num2">
<input type="button" id="boton" value="comprobar" onclick="comprobar()">
    
answered by 02.02.2018 / 14:55
source
1

I think it's because you do not take the value of the numbers, but that you're taking the html object itself, so it goes directly into the else, because the condition of the if is not given, since an html object (the input id = num1 ") is neither even nor odd.

Change this line var num1 = document.getElementById("num1"); by this var num1 = document.getElementById("num1").value;

I hope I have helped you.

Greetings.

    
answered by 02.02.2018 в 14:56
1

Short answer

If you execute console.log(num1); you will see that it returns <input id="num1" type="text"> and that means that the variables num1 and num2 are HTML tags, not their values . To get the values you enter your code should look like this:

var num1 = document.getElementById("num1").innerHTML;
var num2 = document.getElementById("num2").innerHTML;

In depth

When you get elements of DOM , with some of the functions like getElementById() or getElementByClass() you get a node, an HTML element.

This node is an object with its methods and properties. You can set the properties you want to the HTML node, for example in this case:

num1.foo = "bar";
console.log(num1.foo); // Devuelve "bar"

Most browsers have tools to inspect the HTML node tree. If we inspect an element <input> we can see that it has properties value or innerHTML where the values that we enter inside our page are stored.

    
answered by 02.02.2018 в 15:01
0

You lack the value in the two lines where you collect the values:

var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;

And it will work for you.

    
answered by 02.02.2018 в 15:03