-1

I have below codes in my jsp file.

<script>
    $(document).ready(function() {
        var date = new Date();
        var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);

        function getFirstDay() {
            return firstDay;
        }
        ;

        function getToday() {
            return date;
        }
        ;
    });
</script>

<script>
    $('.datepicker').datepicker({
        format : 'yyyy-mm-dd',
        todayHighlight : true
    });

    $("#from_date").datepicker("setDate", getFirstDay());
    $("#to_date").datepicker("setDate", getToday());
    $("#from_date").datepicker('update');
    $("#to_date").datepicker('update');
</script>

But when page load, I got below error on js console.

Uncaught ReferenceError: getFirstDay is not defined 

How could I solve this ?

Bishan
  • 15,211
  • 52
  • 164
  • 258

1 Answers1

6

the function that are to be called you should not put them in document.ready() make them global so that they can be accessible.

change your code to this:

<script>

function getFirstDay() {

        var date = new Date();
        var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
        return firstDay;

        }

function getToday() {

            return new Date();
        }

</script>

and now call it:

<script>
  $(function(){
    $('.datepicker').datepicker({
        format : 'yyyy-mm-dd',
        todayHighlight : true
    });

    $("#from_date").datepicker("setDate", getFirstDay());
    $("#to_date").datepicker("setDate", getToday());
    $("#from_date").datepicker('update');
    $("#to_date").datepicker('update');
 });
</script>
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • ... A warning about how global functions / vars are bad? – Index Aug 16 '14 at 14:57
  • You can simplify `getToday` function by `return new Date();`. Also `getFirstDay` function can be simplified in same way as `getToday` – Regent Aug 16 '14 at 14:58