-5

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>
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
Tyler
  • 1
  • 2
  • This is what I have so far, and it is not working correctly: – Tyler Jun 19 '15 at 22:09
  • @Tyler Put this in your question and ask a more specific question. – t3dodson Jun 19 '15 at 22:10
  • Do not add code in the comments, reedit your question to contain it, click "edit" underneath the question – Patrick Evans Jun 19 '15 at 22:11
  • possible duplicate of [how to sum two numbers from input tag?](http://stackoverflow.com/questions/11961474/how-to-sum-two-numbers-from-input-tag) – JJJ Jun 19 '15 at 22:21

3 Answers3

1

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.

Community
  • 1
  • 1
Tony
  • 2,473
  • 1
  • 21
  • 34
0

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

cs04iz1
  • 1,737
  • 1
  • 17
  • 30
0

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);
redbirdo
  • 4,937
  • 1
  • 30
  • 34