Search code examples
javascriptdate-comparison

getElementByName() for date


I am trying to evaluate inputs on client side using javascript. The getElementByName() method is working for text type inputs. But I want to compare two dates using JS. But getElementByName() is not working for date type inputs! Someone please help! Here is my code:

<script type="text/javascript">
function validate()
{
    var startdate = document.getElementByName("startdate").valueOf();
    alert(startdate);
    var enddate = document.getElementByName("enddate").value;
    submitOK=true;
    if(startdate>enddate)
        {
            alert("start date should not be greater than end date");
            submitOK=false;
        }
    return submitOK;
}
</script>

Solution

  • If you want to get started quickly, add unique ids to both your date inputs, and then use

    document.getElementById("startdate").value;
    

    for example to get both values. And then regarding of their format, a string comparison can be enough (I don't know because you did not mention anything about that), or then you could do something like

    var endDate = document.getElementById("startdate").value;
    endDate = new Date(endDate);
    

    That will give you access to date specific methods that can be handy. More on this here.