jQuery input button click event listener

171,724

Solution 1

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

Solution 2

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

Solution 3

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

Share:
171,724
Bob
Author by

Bob

Updated on October 19, 2020

Comments

  • Bob
    Bob over 3 years

    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?