Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Hide jQdialog on keypress away from .datepicker

I'm using the UP and DOWN arrow keys to navigate through input values.

I am trying to hide the .datepicker when the UP or DOWN arrow key is pressed as follows:-

$('#booking-docket').keyup(function (e) {

    if(e.keyCode === 38 && $("#txt-date").is(":focus") || e.keyCode === 40 && $("#txt-date").is(":focus")) {

        $('#txt-date').datepicker("hide");

    }

});

What is happening is that as soon as the #txt-date element has focus, it quickly opens and closes the datepicker, I thought by adding .is(:focus) would fix this, but that is not the case.

What do I seem to be missing? (not sure if I can hide the datepicker ONLY when the keypress is going away from a text field?)

HTML CODE

        <div class="booking-right left">

            <div class="col-1 left">

                <p class="p-lbl-txt left">TELEPHONE:</p>

                <input type="text" id="txt-telephone" class="input-txt-sml move right" tabindex="5"  />

            </div>

            <div class="col-2 left">

                <p class="p-lbl-txt left">DATE:</p>

                <input type="text" id="txt-date" class="input-txt-sml move right" tabindex="7"  />

            </div>

            <div class="col-1 left">

                <p class="p-lbl-txt left">LEAD TIME:</p>

                <input type="text" id="txt-lead" class="input-txt-sml move right" tabindex="6"  />

            </div>

            <div class="col-2 left">

                <p class="p-lbl-txt left">TIME:</p>

                <input type="text" id="txt-min" class="input-txt-xxsml move right" tabindex="9"  />

                <input type="text" id="txt-hour" class="input-txt-xxsml move right" tabindex="8"  />

            </div>            

        </div>

I've tried the following but couldn't get it to work:-

$(function() {
    $( "#txt-date" ).datepicker({ dateFormat: "dd/mm/yy" });
});

$('#booking-docket').keyup(function (e) {
    /*Add parentheses in your `if` statement to separate the `AND` and `OR`:*/
    if ((e.keyCode === 38 && $("#txt-date").is(":focus"))) {
        $("#txt-lead").focus();//change focus to an other input
        $('#txt-date').datepicker("hide");//hide the datepicker
    }
});
like image 486
nsilva Avatar asked Nov 14 '14 15:11

nsilva


1 Answers

You can use something like this:

JS:

$('#txt-date').keyup(function (e) {
    if ((e.keyCode === 38 && $("#txt-date").is(":focus")) || (e.keyCode === 40 && $("#txt-date").is(":focus"))) {

        if (e.keyCode === 38) $("#txt-telephone").focus();
        else if (e.keyCode === 40) $("#txt-lead").focus();

        $('#txt-date').datepicker("hide");

    }
});

/*Add the datepicker*/
$(function() {
    $("#txt-date").datepicker();
});

JSFIDDLE: http://jsfiddle.net/ghorg12110/ghwvvkve/2/

like image 189
Magicprog.fr Avatar answered Nov 15 '22 08:11

Magicprog.fr