jqueryui datepicker with hidden input

18,276

Solution 1

I did this by doing a .show().focus().hide() - works perfectly though it's a bit unclean:

$(document).ready(function() {
    $('input').datepicker();
        $('#mybutton').click(function() {
        $('input').show().focus().hide();
    });
});

http://jsfiddle.net/JKLBn/

Solution 2

This is a little hacky, but it seems to work okay:

  1. Attach the datepicker to the input instead of the button.
  2. Reposition the datepicker to be underneath the button when it opens.
var $button = $("#date_button"),
    left = $button.offset().left,
    top = $button.offset().top + $button.height();

$('#date_field').datepicker({
    onSelect: function(dateText) {
        $('#date_field').val(dateText);
        $button.text(dateText);
    },
    beforeShow: function (event, ui) {
        setTimeout(function () {
            ui.dpDiv.css({ left: left, top: top });      
        }, 5);               
    }
});

$button.on("click", function() {
    $("#date_field").datepicker("show");
});

Example: http://jsfiddle.net/StUsH/

Share:
18,276

Related videos on Youtube

VMOrtega
Author by

VMOrtega

System analyst bachelor degree 10+ years of experience in software engineering I love Machine Learning

Updated on September 14, 2022

Comments

  • VMOrtega
    VMOrtega over 1 year

    I got a button and a hidden input.

    I want the datepicker opens below the button I click it. And the selected date is inserted in the hidden input.

    I don't want to create a new button (using datepicker options), and I don't wanna show the input.

    <button type="button" class="btn" id="date_button">Select Date...</button>
    
    <input type="hidden" name="date" id="date_field" />
    
    <script>
        $('#date_button').datepicker({
            showOn: "button",
            onSelect: function( dateText ) {
                $('#date_field').val( dateText );
                $('#date_button').text( dateText );
            }
        })
    </script>
    

    Any ideas?

  • LaSul
    LaSul over 10 years
    @J.Ghyllebert I've updated the jsfiddle to a version that works. There appears to be an issue in jsfiddle with jQuery 1.9.1 and jQueryUI 1.9.2, the datepicker chokes on $.browser.msie.
  • Matt S
    Matt S about 10 years
    Instead of using a hidden input, use a text input and hide it with CSS. Initializing the datepicker on a hidden input will cause an error on positioning.