Moshik
Moshik

Reputation: 51

JavaScript - How to disable future dates based on user StartDate selection?

I have this code:

var today = new Date().toISOString().split('T')[0]; 
document.getElementsByName("StartDate")[0].setAttribute('min', today);

$('#StartDate').change(function myfunction() {
    var endDate = new Date($('#StartDate').val());
    $('#ReturnDate')[0].setAttribute('min', endDate);
})

I don't want to use JQuery datepicker, but the html date type. The StartDate is working just fine, but I want to disable dates based on what the user selected in StartDate. For example if the user selected 2015-08-01, than I want all dates until 2015-08-02 in ReturnDate to be disabled. I tried this code, but it is still not working correctly, any ideas?

Upvotes: 1

Views: 620

Answers (2)

Abhitalks
Abhitalks

Reputation: 28437

There are too many problems with your code and you are mixing up Javascript and jQuery calling Javascript methods on jQuery objects.

Hopefully, you will study the code below carefully and then try to find out where you are going wrong and why.

var today = new Date().toISOString().split('T')[0]; 
document.getElementById("startDate").setAttribute('min', today);

$('#startDate').on("change", function() {
    var endDate = new Date(this.value).toISOString().split('T')[0];
    document.getElementById("endDate").setAttribute('min', endDate);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="startDate" type="date" />
<input id="endDate" type="date" />
<input id="btn" type="submit" />

Upvotes: 2

aahhaa
aahhaa

Reputation: 2275

I didn't test it if you are using moment.js, this is something you can do. html datatype is not very good with compatibility, you use write your code for fallback type=text

$('#StartDate').on('change', function() {

    var startDateStr = $(this).value() 
    var StartDateObj = new moment(startDateStr); 

    if($('#EndDate').length) {

        var endDateStr = $('#EndDate').value(); 
        var endDateObj = new moment(endDateStr);

    }

    // you should validate this value 1st, 1/2/15
    // can be read as jan 2 2015, feb 1 2015 depend on the country 

    if(endDateObj.isAfter(StartDateObj)) {

         return true; 

    } else {
         alert('error');
    }


}) 

Upvotes: 0

Related Questions