jQuery KeyUp and Click
Asked Answered
C

6

15

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

Colby answered 3/5, 2011 at 14:38 Comment(0)
S
25
$('#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.

Sil answered 3/5, 2011 at 14:41 Comment(4)
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.Cavesson
Ah, that seems right. @Neal's answer is more appropriate then.Sil
hi - yeah thanks a lot. the aim is to invoke multiple events on multiple objects ?Colby
If it's the same event, you can add multiple objects to the selector: $('#foo, #bar, #baz').bind('click keyup mouseover'), function(...Sil
S
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

Shellishellie answered 3/5, 2011 at 14:40 Comment(0)
P
2
$("#id").click(validate).keyup(function(event)
{
    if (event.keyCode == '13') validate();
});
function validate() { ... validate $(this).val(); ... }
Pugging answered 3/5, 2011 at 14:42 Comment(0)
E
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);
});
Ency answered 3/5, 2011 at 14:42 Comment(0)
B
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
});
Barela answered 19/4, 2013 at 15:44 Comment(0)
B
0

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

            if (!(date_regex.test(event.target.value))) {
                event.target.value = '';
            }
        }
    }
Beverly answered 15/9, 2020 at 5:15 Comment(1)
Please explain how this solves problem. See How To AnswerBabbitt

© 2022 - 2024 — McMap. All rights reserved.