I am building a calculator and have to make it so that every time an operator button is hit, the font turns red.
function changeBtnColor(entry){
if(entry == '+'){
calculator.getElementById("buttonAdd").style.fontcolor = 'red';
calculator.answer.value +=' + ';
}
if(entry == '-'){
calculator.getElementById("buttonSub").style.fontcolor = 'red';
calculator.answer.value +=' - ';
}
if(entry == '*'){
calculator.getElementById("buttonMult").style.fontcolor = 'red';
calculator.answer.value +=' * ';
}
if(entry == '/'){
calculator.getElementById("buttonDiv").style.fontcolor = 'red';
calculator.answer.value +=' / ';
}
}
An example of how I call this js function is:
<form id = "calculator" name=”calculator”>
<table id = "myTable" border = "2">
<tbody>
<tr>
<td colspan = "4">
<input id = "answer" type="text" name="answer"/>
</td>
</tr>
<tr>
<td><input id = "button7" type="button" value="7" onClick="calculator.answer.value +='7'"></td>
<td><input id = "button8" type="button" value="8" onClick="calculator.answer.value +='8'"></td>
<td><input id = "button9" type="button" value="9" onClick="calculator.answer.value +='9'"></td>
<td><input id = "buttonAdd" type="button" value="+" onClick="changeBtnColor('+')"></td>
</tr>
When i do this, I get the error:
calculator.getElementById is not a function
at changeBtnColor (calculator.js:44)
at HTMLInputElement.onclick (calculator.html:21)
Does anyone have any advice for this error or can tell me why it is happening? thanks!
calculatorvariable anywhere? If not, it will beundefined, which is a likely cause of the error you see. (I presume it's supposed to refer to the<form id-"calculator">element, but do you actually assign this anywhere?)var calculator = document.getElementById("calculator"). And actually, now I've looked at your code more closely, none of it will work anyway - becausegetElementByIdonly exists as a method on thedocumentobject, not on any other DOM node..style.color. (fontcoloris not a valid CSS property). I would also suggest it's worth looking at using jQuery - although not essential, it makes DOM and CSS transformations like these a bit less long-winded.