Search code examples
javascriptdatedatepickermootools

date picker in javascript


I am getting no date picker in my web page but in fiddle it is coming, what i am missing?

http://jsfiddle.net/cBwEK/

It is coming fine in fiddle but i am getting nothing in my web page. I have written below scripts

The whole source code is here: http://www.monkeyphysics.com/mootools/script/2/datepicker

<html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>     
    <script type="text/javascript" src="datepicker.js"></script>      
    <script type="text/javascript" src="mootools-yui-compressed.js"></script>
    <script type="text/css" src="datepicker.css"></script>        
    <script type="text/javascript">           
        new DatePicker('.picker', {
            pickerClass: 'datepicker ',
            allowEmpty: true
        });           
    </script>        
 </head>
 <body>
     <label>Datepicker starting at and allowing no value:</label>
     <input name='date_allow_empty' type='text' value='' class='date picker' />
 </body>
</html>

Solution

  • You need to run your JavaScript code after the relevant elements exist in the DOM. Just move the script to the end of the page. Also, if the date picker script relies on MooTools, you need to put the datepicker include after the MooTools include. E.g.:

    <html>
     <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>     
        <!-- FIRST CHANGE HERE, swapping the order of the script elements -->
        <script type="text/javascript" src="mootools-yui-compressed.js"></script>
        <script type="text/javascript" src="datepicker.js"></script>      
        <link type="text/css" rel="stylesheet" href="datepicker.css">
     </head>
      <body>
       <label>Datepicker starting at and allowing no value:</label>
       <input name='date_allow_empty' type='text' value='' class='date picker' />
       <!-- SECOND CHANGE HERE, moving your script to *after* the elements it operates on -->
       <script type="text/javascript">           
                new DatePicker('.picker', {
         pickerClass: 'datepicker ',
         allowEmpty: true
         });           
       </script>        
      </body>
    </html>
    

    Live copy | source

    There I've just moved your script, but you might move all the scripts down there as the YUI people suggest.

    The reason it works in jsFiddle is that you have the fiddle set to load the JavaScript code from the onload event, which happens very late in the process; the DOM elements are there by then.