views:

21

answers:

2

I want to be able to either Press the enter key or click the mouse to submit the info in the inputbox.

Right now when you manually change focus using tab or click with mouse it will submit the info. It is using the jQuery live Click method. I found this solution for setting focus to a button

http://stackoverflow.com/questions/3839342/setting-focus-to-a-button-next-to-a-text-box

but I don't know how to implement that so I can listen using the live click and do either or. A mouse click or the enter button. Any help is appreciated.

example: be able to do this using either the enter button with focus or a mouse click.

$('#theinput').keypress(function(event) { 
  if (event.keyCode == '13') { 
    $('#mybutton').click(); 
    event.preventDefault(); 
  } 
}); 

Problem is I don't know how to convert that example to also use something like this

$('a.button').live('click',function(){
//do stuff here
)};
A: 

I would do this using a named function:

$(document).ready(function(){
    var submitter = function() {
       // do something
    };

    $('#theinput').keypress(function(event) {
        if (event.keyCode == '13') {
            event.preventDefault(); 
            submitter();
        } 
    });

    $('a.button').live('click', submitter);
});

This uses the same function for both events without triggering another unnecessary event, which would cause performance issues.

lonesomeday
That almost works. Somehow it submitting twice because I get double posts. Any idea? Thanks!
Pjack
Could you provide more code? Link/pastebin?
lonesomeday
figured out the problem. I have two buttons one visible and one hidden with the same class on purpose. But for some reason it was submitting both which caused a double post. Even when I tried to use isvisible, it still double posted. When I changed the class name it stopped double posting. I'll have to fix that but the answer seems to do the trick. I did still have to take out the submitter(); from the Keypress or it would also double post. So it works fine as long as you remove the submitter(); from the keypress function. Thanks for the help.
Pjack
A: 

I think if you change this:

$('a.button').live(click,function(){

to this:

$('a.button').live("click",function(){

it should work

cambraca