11

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?

0

3 Answers 3

15

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Does not work in IE with newer jQuery versions. (Probably because IE sets focus asynchronously)
1

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/

2 Comments

@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.
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.
0

I did it different way. I have hidden normal text input by the button with style:

style="outline: none; color:white; margin-top:-20px; border:none;"

so it doesn't appear on the page. It is focusable and it just works fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.