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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bob
  • 1,355
  • 5
  • 19
  • 38
  • possible duplicate of [How to Handle Button Click Events in jQuery?](http://stackoverflow.com/questions/4323848/how-to-handle-button-click-events-in-jquery) – givanse Feb 01 '14 at 15:36

3 Answers3

69

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

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 2
    I'll plus one this just for writing it in one minute, do you have these answers ready to go or what ? – adeneo May 09 '12 at 00:31
  • 4
    @adeneo. Yes... they are stored in a huge DataBase, called my sick and slow brain :) – gdoron May 09 '12 at 00:33
  • I tried that too, but without the `$(function(){...});` part. It works now. Strange. – Bob May 09 '12 at 00:38
  • @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? – gdoron May 09 '12 at 00:40
  • 2
    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` – Bob May 09 '12 at 00:55
6
$("#filter").click(function(){
    //Put your code here
});
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
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(){...})

CHAN
  • 1,518
  • 18
  • 16