Set Values in Input Type Date and Time in JavaScript

set input of type date value from a string

You will have to format the date into YYYY-MM-DD before passing it to the date input.

To do this, you can use:

const str = "29/11/2020";

const [day, month, year] = str.split('/');

const date = `${year}-${month}-${day}`;

<input type="date" value={date} />

How to set default value to the input[type="date"]

The date should take the format YYYY-MM-DD. Single digit days and months should be padded with a 0. January is 01.

From the documentation:

A string representing a date.

Value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.

Your code should be altered to:

<input type="date" value="2013-01-08">

Set Input type=date

Your script is unnecessary, and since property StartDate is a nullable DateTime? and has no value (your html has value="") then var dt = new Date(date); will return Invalid date because var date = $('#StartDate').val(); returns null and the script fails.

You need to set the value of StartDate in the controller before you pass the model to the view, for example

var model = new MyModel() { StartDate = DateTime.Today };
return View(model);

which will display today's date in the input.

In order to display the required format, you can add the DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? StartDate { get; set; }

Note adding the DataTypeAttribute means you can omit the type="date" from your EditorFor() method as that will be added by the method

Alternatively you can omit both attributes and use

@Html.TextBoxFor(m => m.StartDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" }})

Set the value of <input type="date"... in jquery

For input just use .val()

To read the value

  z=$(date).val();

To set the value

$(date).val(today);


Related Topics



Leave a reply



Submit