Skip to content Skip to sidebar Skip to footer

Comparing Two Dates N Times Using Jquery

In here one field named to[0] is used...but actually I have them 'N' times with the +1 in index (to[1],to[2] etc)..which are generating due to cloning... same goes for from[0]. fro

Solution 1:

Just change your selector, then you don't need to duplicate the code. Try this:

//^= means name starts with, so we are selecting all inputs with that matcher
$("input[name^='to['").blur( function() {
    //first we get the name in a variable (just for shortness)var thisName = $(this).prop("name");
    //we then get the numbered index, by splitting the id of the current itemvar index = thisName.substring(thisName.indexOf("[") + 1).replace("]", "");
    //based on the index, we now can get the corresponding "from" fieldvar correspondingFromField = $("input[name='from[" + index + "]']");
    //now we just do your logic:if ($(this).val() != 'To' && correspondingFromField.val() != 'From') {
        var a1 = correspondingFromField.val();
        var b1 = $(this).val();
        alert(b1);alert(a1);
        if (a1 > b1) {
            alert("Invalid Date Range!\nStart Date cannot be after End Date!");
        }
    }
});

Solution 2:

You need to put the counter as part of the selector, but you're hardcoding it to be r. Try this:

while(r<n) {
    if ($('input[name="to\\[' + r + '\\]"]').val() != 'To' && $('input[name="from\\[' + r + '\\]"]').val() != 'From') {
        var a1 = $('input[name="from\\[' + r + '\\]"]').val();
        var b1 = $('input[name="to\\[' + r + '\\]"]').val();
        alert(b1);alert(a1);
        if (a1 > b1) {
            alert("Invalid Date Range!\nStart Date cannot be after End Date!");
        }
    }
    r++;
}

Post a Comment for "Comparing Two Dates N Times Using Jquery"