-1

Not sure if I am obtaining the correct object in the following javascript code:

<form>
    What is 5 + 5?: <input type ="number" id ="num_answer;"/>
</form>
<script>
    function basic_math(){
        var num_val = document.getElementById('num_answer').value;
        if (num_val == 10) {
            document.getElementById('num_answer').style.backgroundColor = green;
        }
        else{
            document.getElementById('num_answer').style.backgroundColor = red;
        }
    }
</script>


<button type = "button" onclick ="basic_math();"> Solve! 
</button>

The error that I am getting:

    Uncaught TypeError: Cannot read property 'value' of null 
4

3 回答 3

2

去掉那个分号:

What is 5 + 5?: <input type ="number" id ="num_answer;"/>
<!--                              This is a typo     ^           -->
于 2013-08-28T21:37:22.047 回答
2

它应该是:

<input type ="number" id="num_answer"/>

(没有分号)

于 2013-08-28T21:37:31.253 回答
1

这是一个使用 JQuery 的解决方案

<p> <span> What is 5 + 5? </span> 
  <input type="number" id="num_answer" />    </p>    

function basic_math()
{   
   num_val = $("#num_answer").val();
   if (num_val == 10) {
    $('#num_answer').css("color", "white");
    $('#num_answer').css("background-color", "green");
   } else {

     $('#num_answer').css("background-color", "red");

     }
}

http://jsfiddle.net/fonsecat/WMJh3/17/

于 2013-08-28T22:28:15.150 回答