How to extract values from HTML <input type=“date”> using jQuery

后端 未结 5 1344
无人及你
无人及你 2020-12-16 12:38

Using an HTML input type=\"date\" and a submit button. I would like to populate the variables day, month, and year with t

相关标签:
5条回答
  • 2020-12-16 12:49

    Firstly you need to create a Date object from input element value. And then you will be able to get day, month and year from this object.

    $('#submit').on('click', function(){
      var date = new Date($('#date-input').val());
      day = date.getDate();
      month = date.getMonth() + 1;
      year = date.getFullYear();
      alert([day, month, year].join('/'));
    });
    

    Working example: https://jsfiddle.net/8poLtqvp/

    0 讨论(0)
  • 2020-12-16 12:50
    date = new Date($('#date-input').val())
    date.getDate()
    

    ...

    0 讨论(0)
  • 2020-12-16 12:57
            <input type="date" id="date-input"/>
            <input type="submit" id="submit" value="submit"/>
    
    
    <script>
          $('#submit').on('click', function(){
                  var date = new Date($('#date-input').val());
                  var day = $('#date-input').getDate();
                  var month = $('#date-input').getMonth() + 1;
                  var year = $('#date-input').getFullYear();
                  alert(day+"/"+ month+"/"+year);
                });
        </script>
    

    Date class will convert input data into date type. Then getMonth() gives us value from 0-11 so we can either consider January as 0 or we can add 1 to received value that's what I did here.

    Here I just used Jquery to fetch date, months and year respectively and if you want to post the data you can convert that values into string.

    0 讨论(0)
  • 2020-12-16 13:06

    The Advantage of JQuery ? A few lines of code do a lot !!

    alert only takes a string as its parameter. So simply, we just have to pass our Date object as a string using th String built-in-Function.

    Just replace the button tag with this...

    <button onclick="alert(String( $("#date-input").val() ))">Submit</button>
    

    You can do further manipulations on the string you'll be alerted as yyyy-mm-dd

    0 讨论(0)
  • 2020-12-16 13:15

    Date value returned by input type="date" is format yyyy-mm-dd . Could use .split() with argument "-" to retrieve array containing [yyyy, mm, dd]

    Note, alert() expects string as parameter ; does not print values same as console.log() with comma , operator

    var day, month, year;
    
    $('#submit').on('click', function() {
      var date = $('#date-input').val().split("-");
        console.log(date, $('#date-input').val())
      day = date[2];
      month = date[1];
      year = date[0];
      alert(day + month + year);
    });
    

    jsfiddle https://jsfiddle.net/dkxy46ha/2/

    0 讨论(0)
提交回复
热议问题