JQuery UI Datepicker loses focus when selecting date with mouse

后端 未结 10 1550
情歌与酒
情歌与酒 2021-02-01 02:16

I am using JQuery ui with datepicker and when a user tabs on to a field, they appropriately get the calendar pop up.

  1. User tabs (via key onto field
  2. User s
相关标签:
10条回答
  • 2021-02-01 02:41

    Having it focus on the same box ultimately causes the date picker to pop back up and what we really want is for it to go to the next field. Here is teh devised solution:

    1. Requires the tabindex attribute to be set on your fields.
    2. This is casting from a string to int in javascript (the * 1).
    3. This actually moves the selected field to the next element, instead of the current focus

      $(function(){
        $(".date").datepicker({
            onSelect: function(){
                currenttab = $(this).attr("tabindex");
                nexttab = currenttab * 1 + 1;
                $(":input").each(function(){
                    if ($(this).attr("tabindex") == nexttab)
                       $(this).focus();
                });
        }
        });
      });
      

    Any suggestions to improve on this technique are appreciated.

    0 讨论(0)
  • 2021-02-01 02:51

    If you really don't care about the tab order, that is, not having it assigned so it follows the flow of the page, you could do something like this.

    jQuery('.date').datepicker({
        'onSelect': function(){
            $(this).nextAll('input, button, textarea, a').filter(':first').focus();
        }
    });
    

    It works on the assumption that when the user selects the date, he is finished with that field and moves on to the next one, so it simply selects the next field.

    0 讨论(0)
  • 2021-02-01 02:53

    I have added an empty href tag next to the datepicker input control and focus onto it in the onClose event handler. This solved my problem of the focus shifting all the way to the top of the page when the calendar was closed. I am using that href tag to display error messages; therefore it serves two purposes for me.

    0 讨论(0)
  • 2021-02-01 02:54

    Thanks for the suggestion Jeff, I modified your onSelect function to use the attribute filter to retrieve only elements with the tabindex specified by "nexttab".

    $(function(){
      $(".date").datepicker({
          onSelect: function(){
              currenttab = $(el).attr("tabindex");
              nexttab = currenttab * 1 + 1;
              $("[tabindex='" + nexttab + "']").focus();
          }
      });
    });
    

    PS: If you don't have tabindexes specified in your code, like I neglected to do earlier, simply add the following code:

    $('input, select').each(function(i, val){
        $(this).attr('tabindex', i + 1);
    });
    
    0 讨论(0)
提交回复
热议问题