Open JQuery Datepicker by clicking on an image w/ no input field

后端 未结 8 896
夕颜
夕颜 2020-11-27 13:00

I want to have the JQuery Datepicker open when the user clicks on an image. There is no input field where the selected date appears afterwards; I\'m just going to save the e

相关标签:
8条回答
  • 2020-11-27 13:48

    Having a hidden input field leads to problems with datepicker dialog positioning (dialog is horizontally centered). You could alter the dialog's margin, but there's a better way.

    Just create an input field and "hide" it by setting it's opacity to 0 and making it 1px wide. Also position it near (or under) the button, or where ever you want the datepicker to appear.

    Then attach the datepicker to the "hidden" input field and show it when user presses the button.

    HTML:

    <button id="date-button">Show Calendar</button>
    <input type="text" name="date-field" id="date-field" value="">
    

    CSS:

    #date-button {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        height 30px;
    }
    
    #date-field {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 1px;
        height: 32px; // height of the button + a little margin
        opacity: 0;
    }
    

    JS:

    $(function() {
       $('#date-field').datepicker();
    
       $('#date-button').on('click', function() {
          $('#date-field').datepicker('show');
       });
    });
    

    Note: not tested with all browsers.

    0 讨论(0)
  • 2020-11-27 13:49

    The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:

    <img src='someimage.gif' id="datepickerImage" />
    <div id="datepicker"></div>
    
    <script type="text/javascript">
     $(document).ready(function() {
        $("#datepicker").datepicker({
                changeMonth: true,
                changeYear: true,
        })
        .hide()
        .click(function() {
          $(this).hide();
        });
    
        $("#datepickerImage").click(function() {
           $("#datepicker").show(); 
        });
     });
    </script>
    
    0 讨论(0)
提交回复
热议问题