Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to use modifier keys on form submit?

Say I have a form that looks like this:

[ Animal name input field ] Add button

If I type a name and hit enter, an animal with the given name is added to a table. Works fine. What I would like now is to call the current way of working "quick add" and add a new feature called "slow add", which I am not quite sure how to do. Basically what I want is that if for example the shift key is held down when enter or the button is clicked, I want the form submit method to do something slightly different. In my case I want it to open up a form where more details on the animal can be added before it is added to the table.

Problem is I'm not quite sure how to do this. I have tried add a FireBug console.info(eventData) in my current submit function and I have found that the eventData contains an altKey, shiftKey and controlKey property, but they are always undefined even when I hold those keys down.

So, does anyone know how I can do something special in my submit handler when certain modifier keys were pressed when the form was submitted?


Temporary solution

Ended up ignoring the submit-button-shift-click-feature and instead just have the quick add feature as shift-enter-in-input-fields. Implemented it something like this:

$('#new-task')
    .submit(onNewAnimal)
    .keypress(onNewAnimal);


function onNewAnimal(event)
{
    if(event.type == 'keypress' && event.which != 13)
        return true;

    if(event.shiftKey)
    {
        // Quick add
    }
    else
    {
        // Open slow add dialog
    }

    return false;
}

Still curious if there is a better way, but until then, this is what I have. Maybe it can help someone else as well :)

like image 813
Svish Avatar asked Nov 14 '22 10:11

Svish


1 Answers

You may get shift pressed by $(document).keyup and $(document).keydown events. For example my code for control key is

$(document).keyup(function (e) {
    if (e.which == 17) $.isCtrl=false;
}).keydown(function (e) {
    if (e.which == 17) $.isCtrl=true;
});

And just check

if ($.isCtrl) { ... }

in your handler

like image 163
Dim_K Avatar answered Dec 09 '22 20:12

Dim_K