Here is a boolean-logic

645 views Asked by At

Write a JavaScript function named findTen that reads two numbers from two text fields and then outputs to a div "True" if either one of them is 10 or both of them are 10 or if their sum is 10. Otherwise your function should output "False" to the div.

This is what I have so far, but it is not outputting correctly. Something is wrong with my else if statement:

<script> 
function findTen()  {
    var a = document.getElementById("one").value;
    var b = document.getElementById("two").value;
    var doTheMath = a + b;

    if ( a == 10 || b == 10)  {
        alert("true");
    }
    else if (doTheMath == 10 ) {
        alert("true");
    }
    else {
        alert(a b doTheMath);
    }
    document.getElementById("output").innerHTML = c;
}
</script>
3

There are 3 answers

0
cs04iz1 On

Your problem is that it handles the inputs as Strings and not as integers. what you have to do is make the strings into integers by using the parseInt function

0
redbirdo On

Your a and b variables are strings because you just got them out of text fields. In JavaScript, if you use the + operator on strings it will concatenate them. This is rather unfortunate 'feature' of javascript. To add the values from text fields you first need to convert them to integers:

var doTheMath = parseInt(a) + parseInt(b);

Furthermore, I don't think this statement will work at all:

alert(a b doTheMath);

Alert takes a string, so if you want to display those three values you'll need to concatenate them e.g.

alert(a + ' + ' + b + ' = ' + doTheMath);
0
Tony On

There are a few errors in your posted code:

  1. a and b are strings, so doTheMath is actually a string. In the case of a = 5 and b = 5, doTheMath is '55'. They need to be converted, in one of a number of ways. I chose Number:

    var doTheMath = Number(a) + Number(b);

  2. alert(a b doTheMath) is improper syntax. You should look to concat them:

    alert(a + ' ' + b + ' ' + doTheMath);

  3. c is undefined in your assignment at the end. So in your if/else blocks you probably want a statement like: c = false;

You can see all these problems fixed in this jsfiddle.