Search code examples
phpjquerylaraveljquery-ui-datepicker

jQuery datepicker not working - Laravel app


I contained my datepicker input inside if statement, so it doesn't work. I don't know whether it isn't working because of if statement or else, but when there is no if statement, datepicker works fine. Scripts are included in right order, so that is fine. jQuery scripts:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
 $(function() {   
 $('#nextDate').datepicker({
    dateFormat: "yy-mm-dd", 
    });
    $("#currentDate").datepicker({
    dateFormat: "yy-mm-dd", 
    minDate:  0,
    onSelect: function(date){
        var date2 = $('#currentDate').datepicker('getDate');
        date2.setDate(date2.getDate()+7);
        $('#nextDate').datepicker('setDate', date2);
        }
    });
 });
 </script>

The page where datepicker should be, stands like this:

if(Auth::user()->role == 2) { ?>
<form class="form-horizontal" method="POST" action="/rentals">
{{ csrf_field() }}
    <div class="form-group">
            <div class="col-sm-5 col-sm-offset-1">
                <input class="form-control" type="text" id="currentDate" name="start">
            </div>
            <div class="col-sm-5">
            <input class="form-control" type="text" id="nextDate" name="end">
            </div>
    </div>
        <button type="submit" class="btn btn-success">Rent it</button>
        </form>
 <?php } ?>

Solution

  • Have you tried to initiate the datePickers from the console simply with:

    $('#nextDate').datepicker({});
    

    If so what errors do you get? This may not be the actual answer but another thing to try would be to put wrap your javascript code document ready rather than the function you are using now:

    $(document).ready(function(){
    
        $('#nextDate').datepicker({
            dateFormat: "yy-mm-dd", 
        });
    
        $("#currentDate").datepicker({
            dateFormat: "yy-mm-dd", 
            minDate:  0,
            onSelect: function(date){
                var date2 = $('#currentDate').datepicker('getDate');
                date2.setDate(date2.getDate()+7);
                $('#nextDate').datepicker('setDate', date2);
            }
        });
    });
    

    Also I would recommend removing the options from the datepicker calls when testing. Sometimes they are the source of the error so start with just:

    $(document).ready(function(){
        $('#nextDate').datepicker();
        $('#currentDate').datepicker();
    });