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
Get rid of that semi-colon:
What is 5 + 5?: <input type ="number" id ="num_answer;"/>
<!-- This is a typo ^ -->
It should be:
<input type ="number" id="num_answer"/>
(No semi-colon)
Here is a solution that uses 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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.