I have the following JavaScript code, it appears to be correct.
I simply want, on button Click, for the background of the textbox to turn 'red', if the textbox is left blank.
Can someone point out the error in the below code.
function validate(){
if (document.getElementById("textbox_1").value==' '){
document.getElementById("textbox_1").style.backgroundColor='red';
}
}
<body>
NAME:<INPUT TYPE="Text" SIZE="15" VALUE="" ID="textbox_1" />
<INPUT TYPE="Button" VALUE="SEND" onClick="Validate()" />
</body>
Uppercase/Lowercase matters (in function name). You also should compare against empty string not blank space:
<script>
function validate(){
var el = document.getElementById("textbox_1");
if (el.value.trim()==''){
el.style.backgroundColor='red';
}
else{
el.style.backgroundColor='';
}
}
</script>
NAME:<INPUT TYPE="Text" SIZE="15" VALUE="" ID="textbox_1">
<INPUT TYPE="Button" VALUE="SEND" onClick="validate()">