Copper
Copper

Reputation: 35

How to set a value to an input that is smaller than min or larger than max?

EDIT: The issue was simply that some of the data I was attempting to place into the input was in an incorrect format. Look at the accepted answer to read more.

I am working with an input field that has the type="datetime-local". I have also set min and max values to said input. I would like to still add values to it through JavaScript that break these constraints, being smaller than the minimum date or larger than the maximum date. However, currently just setting the value (in this case a value smaller than min), causes the time portion of the input to become blank, like so:

Blank time

datetimeInput = document.createElement('input');
datetimeInput.setAttribute('type','datetime-local');
datetimeInput.setAttribute('step','1');
datetimeInput.setAttribute('min', minTime);
datetimeInput.setAttribute('max', maxTime);

if (data) {
  datetimeInput.value = data.time;
}

Upvotes: 0

Views: 622

Answers (1)

CyberDev
CyberDev

Reputation: 226

Every country or region has its own datetime format. The default value format for a datetime-local type <input> tag in my region is:

YYYY-MM-DDTHH:MM

If I was to set the value of my <input> element to the following:

datetimeInput.value = "2017-12-31T00:00";

This will result in the value being assigned and the input tag will now show you the datetime value assigned through javascript.

See this working in the following snippet. You can then use your region's default format to set the value:

datetimeInput = document.createElement('input');
datetimeInput.setAttribute('type', 'datetime-local');
datetimeInput.setAttribute('step', '1');
datetimeInput.setAttribute('min', "2018-06-07T00:00");
datetimeInput.setAttribute('max', "2018-06-14T00:00");

datetimeInput.value = "2017-12-31T00:00";

document.getElementById("main").appendChild(datetimeInput);
<div id="main"></div>

Upvotes: 1

Related Questions