开发者

How can I toggle a calendar or datepicker in an overlay when clicking a link?

I'm trying to attach the jQuery datepicker to a hyperlink vs the conventional input element. I know this has already been talked about here and there which led me to this implementation:

$(document).ready(function()
{
  var picker_link_id = "datepicker_link"
  var picker_div_id  = "datepicker"

  var picker_div = $("#" + picker_div_id)

  // initialize the datepicker
  picker_div.datepicker({
    onSelect: 
      function(dateText, picker) {
        picker_div.hide();
        // custom work
      }

  });

  // position & toggle the datepicker on link click
  $("#" + picker_link_id).click(function() {
    var $this = $(this)

    // position the datepicker
    picker_div.css('position', 'absolute');
    picker_div.css('left', $this.position().left - (picker_div.width() - $this.width()));

    picker_div.toggle()

    return false;
  });

  // pressing ESC or clicking outside the datepicker should close it
  $(document)
    .bind("keypress", function(e) {
      if ( e.keyCode == 27 )
        picker_div.hide();
    })
    .bind("mousedown", function(e) {
      if ( e.target.id == $("#" + picker_link_id)[0].id )
        return;

   开发者_StackOverflow社区     if ( e.target.id != picker_div_id  && $(e.target).parents('#' + picker_div_id).length == 0 )
            picker_div.hide();
    });
});

In my view, I have the following HTML:

<a href="#" id="datepicker_link">September 26, 2011</a>             
<div id="datepicker"></div>

Even though the above works, it seems like I'm re-creating some jQuery logic. Is there a better way to do this?


One alternative is to use an input element, instead of a div one, and position the input element out of the sight of the screen. Then you will be able to make use of the .datepicker('show') and .datepicker('hide').

Then you can position the datepicker div with a css rule, such as the following one:

#ui-datepicker-div {
    top: 50px !important;
    left: 50px !important;
}

Note the !important keyword needs to be used, to effectively override the dynamic position.

See an example here: http://jsfiddle.net/william/VCQsk/.


$('#datepicker').datepicker('show');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜