I'm just trying to create a simple button to check if an input field is empty and style it accordingly. I feel like this should be really simple but I'm just missing something.
<input id="text"></input>
<button id="button">check</button>
<script>
var text = document.getElementById('text');
var button = document.getElementById('button');
function checker() {
if (text.value === "") {
text.style.cssText = "background:red;";
return false;
}
else {
text.style.cssText = "background:green;";
}
}
button.addEventListener("click", checker(), false);
</script>
And here's the link to a jsfiddle that I was using to try and get it to work.
Instead of passing a reference to the checker()
function, you are actually calling the function and passing the result.
What you want to do is pass a reference to the function like this...
button.addEventListener("click", checker, false);
Note the lack of ()
You need to pass the function by reference:
button.addEventListener("click", checker, false);
Note: you could also pass an anonymous function:
button.addEventListener("click", function(){checker();}, false);
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.