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
Keep Selected Dropdown Result After Refreshing Page, Jquery
Concatenate Json to a String in JavaScript
Dynamically Increase and Decrease an Input Text Box Size Depending on Another Selector Width
Correct Way to Push into State Array
How to Detect String Which Contains Only Spaces
Ngx-Datatable Set Column Width Dynamically
Why Does This Onclick Event Not Work in an HTML Iframe
How to Display Loading Message When an Iframe Is Loading
How to Add Active Class/State for Li Element in Reactjs
Set Cookie on Page Load and Hide Div If Cookie Is Present
How to Make One Observable Sequence Wait for Another to Complete Before Emitting
Disable Chrome Strict Mime Type Checking
Read Lines of a Txt File and Organize in a Json File
Force Download a Pdf Link Using Javascript/Ajax/Jquery
Passing Variable from One Js to Another Js File in Nodejs
Convert Milliseconds to Hours and Minutes Using Momentjs