14

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

MMM
  • 7,221
  • 2
  • 24
  • 42
Tom
  • 143
  • 1
  • 1
  • 4

6 Answers6

24
$('#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.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • I initially thought this too, but it doesn't look like the OP really wants to bind multiple events to a DOM object, but instead have multiple events on multiple objects invoke the same code. – justkt May 03 '11 at 14:43
  • Ah, that seems right. @Neal's answer is more appropriate then. – Blender May 03 '11 at 14:45
  • hi - yeah thanks a lot. the aim is to invoke multiple events on multiple objects ? – Tom May 03 '11 at 14:45
  • 2
    If it's the same event, you can add multiple objects to the selector: `$('#foo, #bar, #baz').bind('click keyup mouseover'), function(...` – Blender May 03 '11 at 14:49
3

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

Naftali
  • 144,921
  • 39
  • 244
  • 303
2
$("#id").click(validate).keyup(function(event)
{
    if (event.keyCode == '13') validate();
});
function validate() { ... validate $(this).val(); ... }
Mo Valipour
  • 13,286
  • 12
  • 61
  • 87
2

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);
});
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
1

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
});
fidoogle
  • 91
  • 3
0

function checkEnter(event) { if (event.keyCode === 13) {

            if (!(date_regex.test(event.target.value))) {
                event.target.value = '';
            }
        }
    }
  • Please explain how this solves problem. See [How To Answer](https://stackoverflow.com/help/how-to-answer) – jasie Sep 15 '20 at 06:09