making a calculation using JavaScript

Why this isn't working? I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..

    <script type="text/javascript">
    function calculate() {
       var calculateit=document.getElementById('disp');
       var pluscharacter=/+/;
       var matchplus=calculateit.search(pluscharacter);
       var inputlength=calculateit.length;
           if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
              answer=calculateit[0]+calculateit[1];
              alert("Your answer is: "+answer+" Is it?");
    }
    }
    </script>

Upvotes: 0

Views: 50

Answers (3)

You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:

https://jsfiddle.net/mckinleymedia/9ezky35v/2/

With this HTML:

<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>

You can use this script:

function calculate() {
  var calculateit = document.getElementById('disp').innerHTML.trim(),
      numbers = calculateit.split('+'),
      answerDiv = document.getElementById('answer');
  if ( numbers.length > 1 ) {
    answer = parseInt(numbers[0]) + parseInt(numbers[1]);
    answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
  } else {
    answerDiv.innerHTML = "I can't calculate that equation.";
  }
}
calculate();

Upvotes: 0

brandonscript
brandonscript

Reputation: 73044

Your if statement isn't a valid condition. Try:

if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)

Upvotes: 2

Ramanlfc
Ramanlfc

Reputation: 8354

var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);

calculateit is a Node doesn't have any search() method.

Upvotes: 1

Related Questions