34

Brand new to jQuery. I was trying to set up an event listener for the following control on my page which when clicked would display an alert:

<input type="button" id="filter" name="filter" value="Filter" />

But it didn't work.

$("#filter").button().click(function(){...});

How do you create an event listener for a input button control with jQuery?

1

3 Answers 3

68

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

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

5 Comments

I'll plus one this just for writing it in one minute, do you have these answers ready to go or what ?
@adeneo. Yes... they are stored in a huge DataBase, called my sick and slow brain :)
I tried that too, but without the $(function(){...}); part. It works now. Strange.
@Bob. So or you leave the $(function(){...}) part and put the js after the button, or you keep it and don't worry if the location will change in the future. Did you get with it helped you?
Yeah I got it. Just like you said: This insure the DOM is ready before the function runs, so it doesn't matter if the function is written above the button, it'll wait until the button is loaded and then attach it the click callback
6
$("#filter").click(function(){
    //Put your code here
});

Comments

4

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

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.