0

I have the following HTML:

<div class="l-dbDetails"> 
    <label>Start Date: </label>
    <input type="date" id="l-StartDate" name="StartDate" value="2017-04-03" size="29px" class="l-required" required=""><br>
</div>

This gives me a nice date picker field in which I can choose a date.

I then need to get the date from this field using jQuery, so I use:

startDate = $('#l-StartDate').attr('value');

But this always returns the default value of "2017-04-03". How can I make jQuery pick up the new date?

IGGt
  • 2,627
  • 10
  • 42
  • 63

1 Answers1

1

so I use ...attr('value')

The current value of an input isn't its value attribute. To get the current value with jQuery, use .val(), not .attr('value'):

startDate = $('#').val();

The value will be a string.

On modern browsers with up-to-date handling for type="date" inputs, you can also use the underyling HTMLInputElement's valueAsDate property:

startDate = $('#l-StartDate').prop("valueAsDate");

Example:

$("#l-StartDate").on("change", function() {
  var $this = $(this);
  console.log("String: ", $this.val());
  console.log("Date: ", $this.prop("valueAsDate"));
});
<input type="date" id="l-StartDate">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Details:

The value attribute controls the default value of the input, and doesn't change as the user changes the value. That attribute is reflected by the defaultValue property of the underlying HTMLInputElement. The current value is reflected by the value property of that input (which isn't stored as an attribute at all). jQuery's val accesses the value property of the HTMLInputElement.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    I don't know why I was doing that way (I'm sure it made sense at some point in time!!!). Cheers for the great explanation. – IGGt May 03 '17 at 14:01