1

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.

Link

2
  • Why aren't you using jquery? It's much more easy and you can use the function .submit on a form api.jquery.com/submit Commented Apr 4, 2014 at 16:41
  • Well, I'm just starting to learn javascript and I figured I'd learn that first to at least get the basics down before I tried to learn anything else like jquery. Commented Apr 4, 2014 at 17:13

2 Answers 2

5

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 ()

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help and for such a fast response!
Not a problem - easy to spot when you know what you're looking for. Good luck with your journey into javascript/jquery :-)
4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.