Need to store html date input in JS var

Viewed 649

I need help with JS and html. I need to store <input type = "date" id = "date"> in JS var. If you try to store the date in simple var and try to print it instead of your chosen date you get printed "undefined" :

$("#printDate").click(function(){
   var dateVar = ($("#date").val());
    $("#results").append("<p>" + dateVar + "</p>")
});

If you try to store the date in the dateVar using new Date() you get printed "Invalid date": enter image description here

$("#printDate").click(function(){
   var dateVar =  new Date($("#date").val());
    $("#results").append("<p>" + dateVar + "</p>")
});

Thank you for any kind of help!

upd: full page code:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    `<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">`</script>
</head>
<body>

    <div id="results"></div>

    <input type="date" id = "dateInput">
    <button id = "printDate">PrintDate</button>

           <script>
        $("#printDate").click(function(){
           var dateVar =  new Date($("#date").val());
            $("#results").append("<p>" + dateVar + "</p>")
        });
    </script>
</body>
</html>
2 Answers

$("#printDate").click(function(){
           var dateVar =  new Date($("#dateInput").val());
           $("#results").append("<p>" + dateVar + "</p>")
});
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">`</script>
</head>
<body>

    <div id="results"></div>

    <input type="date" id = "dateInput">
    <button id = "printDate">PrintDate</button>

</body>
</html>

The only problem with your code is you are targetting wrong id i.e $("#date") instead of $("#dateInput")

<div id="results"></div>

<input type="date" id="dateInput">
<button id="printDate">PrintDate</button>

       <script>
    $("#printDate").click(function(){
       var dateVar =  new Date($("#dateInput").val());
        $("#results").append("<p>" + dateVar + "</p>")
    });
</script>

You have a typing error.

Related