Bob
Bob

Reputation: 1375

jQuery input button click event listener

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?

Upvotes: 34

Views: 185342

Answers (3)

CHAN
CHAN

Reputation: 1566

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(){...})

Upvotes: 4

gdoron
gdoron

Reputation: 150253

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

Upvotes: 69

Danilo Valente
Danilo Valente

Reputation: 11342

$("#filter").click(function(){
    //Put your code here
});

Upvotes: 6

Related Questions