Question

I was wondering how you can do .keyup() and .click() for the same #id?

i.e. essentially I want to validate the #id when both the user attempts to hit enter or hits the #search button.

Thanks alot

Was it helpful?

Solution

$('#foo').bind('click keyup', function(event) {
  ...

You'll have to add some logic, as the event type changes, but it should work with enough if blocks.

OTHER TIPS

Well you can do:

        $(document).keydown(function(objEvent) {
            if (objEvent.keyCode == 13) {  //clicked enter
                 $('#search').click(); //do click
            }
        })

        $("#search").click(function(e){/*click fn*/})

Will run the click on enter press

$("#id").click(validate).keyup(function(event)
{
    if (event.keyCode == '13') validate();
});
function validate() { ... validate $(this).val(); ... }

I'd go for something like this:

function validate(element) {
     // your validation stuff goes here
}

$('#id').keyup(function(event) {
    if (event.keyCode == 13) {  
        validate(this);
    }
}).click(function() {
    validate(this);
});

The new jQuery offers the which property on the event to check which key was pressed so yo can do something like this now:

$(#id").on('keyup',function(e){
    if (e.which==13 || e.which==9) doSomething(this); //Enter or Tab key
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top