Форма ввода в HTML5

Html label display date

Для работы с датами и временем в HTML5 предназначено несколько типов элементов input:

  • datetime-local : устанавливает дату и время
  • date : устанавливает дату
  • month : устанавливает текущий месяц и год
  • time : устанавливает время
  • week : устанавливает текущую неделю

Например, используем поле для установки даты:

       

И при вводе в поле для даты будет открываться календарик:

Установка даты в HTML5

Правда, здесь надо отметить, что действие этого элемента зависит от браузера. В данном случае используется Google Chrome. В последних версиях Opera элемент не будет сильно отличаться. А вот в Microsoft Edge элемент будет выглядеть так:

Установка даты в Microsoft Edge

Применение остальных элементов:

       

Дата и время в HTML5

При использовании этих элементов также надо учитывать, что Firefox поддерживает только элементы date и time , для остальных создаются обычные текстовые поля. А IE11 и вовсе не поддерживают эти элементы.

Источник

Html label display date

elements of type date create input fields allowing a date to be easily entered — this includes year, month and day, but not time . The control’s UI varies in general from browser to browser; at the moment support is patchy, see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to a simple .

For those of you not using a supporting browser, the Chrome/Opera date control looks like so: and the Edge date control looks like this:

Value A DOMString representing a date, or empty
Events change and input
Supported Common Attributes autocomplete , list , readonly , and step
IDL attributes list , value , valueAsDate , valueAsNumber .
Methods select() , stepDown() , stepUp()

Value

A DOMString representing the value of the date entered into the input. You can set a default value for the input by including a date inside the value attribute, like so:

One thing to note is that the displayed date format differs from the actual value — the displayed date format will be chosen based on the set locale of the user’s operating system, whereas the date value is always formatted yyyy-mm-dd . You can also get and set the date value in JavaScript using the HTMLInputElement.value property, for example:

var dateControl = document.querySelector('input[type="date"]'); dateControl.value = '2017-06-01';

Using date inputs

Date inputs sound convenient at first glance — they provide an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user’s locale. However, there are issues with because of the limited browser support. We’ll look at basic and more complex uses of , then offer advice on mitigating the browser support issue later on (see Handling browser support).

Basic uses of date

Setting maximum and minimum dates

You can use the min and max attributes to restrict the dates that can be chosen by the user. In the following example we are setting a minimum date of 2017-04-01 and a maximum date of 2017-04-30 :

 

The result here is that only days in April can be selected — only the «days» part of the text value will be editable, and dates outside April can’t be scrolled to in the datepicker widget.

Читайте также:  Html form две кнопки

Note: You should be able to use the step attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.

Controlling input size

Validation

By default, does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still not fill in a date and submit, or enter an invalid date (e.g. the 32th of April). If you use min and max to restrict the available dates (see anch(«Setting maximum and minimum dates»)), supporting browsers will display an error if you try to submit a date that is outside the set bounds. In addition, you can use the required attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. Let’s look at an example — here we’ve set minimum and maximum dates, and also made the field required:

   

If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: Here’s’a screenshot for those of you who aren’t using a supporting browser: Here’s the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.

div < margin-bottom: 10px; display: flex; align-items: center; >label < display: inline-block; width: 300px; >input:invalid+span:after < content: '✖'; padding-left: 5px; >input:valid+span:after

Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).

Читайте также:  New pdo php select

Handling browser support

As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this: Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the most serious — as we mentioned earlier, with a date input the actual value is always normalized to the format yyyy-mm-dd . With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:

  • ddmmyyyy
  • dd/mm/yyyy
  • mm/dd/yyyy
  • dd-mm-yyyy
  • mm-dd-yyyy

One way around this is to put a pattern attribute on your date input. Even though the date input doesn’t use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:

If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if you entry doesn’t match the pattern nnnn-nn-nn , where n is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm (whereas we want yyyy-mm-dd ). So we still have a problem.

div < margin-bottom: 10px; >input:invalid + span < position: relative; >input:invalid + span:after < content: '✖'; position: absolute; right: -18px; >input:valid + span < position: relative; >input:valid + span:after

The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls ( elements being popular — see below for an implementation), or use a JavaScript library such as jQuery date picker.

Examples

In this example we create two sets of UI elements for choosing dates — a native picker, and a set of three elements for choosing dates in older browsers that don’t support the native input.

 

Enter your birthday:

The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)

input:invalid+span:after < content: '✖'; padding-left: 5px; >input:valid+span:after
// define variables var nativePicker = document.querySelector(‘.nativeDatePicker’); var fallbackPicker = document.querySelector(‘.fallbackDatePicker’); var fallbackLabel = document.querySelector(‘.fallbackLabel’); var yearSelect = document.querySelector(‘#year’); var monthSelect = document.querySelector(‘#month’); var daySelect = document.querySelector(‘#day’); // hide fallback initially fallbackPicker.style.display = ‘none’; fallbackLabel.style.display = ‘none’; // test whether a new date input falls back to a text input or not var test = document.createElement(‘input’); test.type = ‘date’; // if it does, run the code inside the if() <> block if(test.type === ‘text’) < // hide the native picker and show the fallback nativePicker.style.display = 'none'; fallbackPicker.style.display = 'block'; fallbackLabel.style.display = 'block'; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); >function populateDays(month) < // delete the current set of elements out of the // day , ready for the next set to be injected while(daySelect.firstChild) < daySelect.removeChild(daySelect.firstChild); >// Create variable to hold new number of days to inject var dayNum; // 31 or 30 days? if(month === ‘January’ | month === ‘March’ | month === ‘May’ | month === ‘July’ | month === ‘August’ | month === ‘October’ | month === ‘December’) < dayNum = 31; >else if(month === ‘April’ | month === ‘June’ | month === ‘September’ | month === ‘November’) < dayNum = 30; >else < // If month is February, calculate whether it is a leap year or not var year = yearSelect.value; (year - 2016) % 4 === 0 ? dayNum = 29 : dayNum = 28; >// inject the right number of new elements into the day for(i = 1; i // if previous day has already been set, set daySelect’s value // to that day, to avoid the day jumping back to 1 when you // change the year if(previousDay) < daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if(daySelect.value === "") < daySelect.value = previousDay - 1; >if(daySelect.value === «») < daySelect.value = previousDay - 2; >if(daySelect.value === «») < daySelect.value = previousDay - 3; >> > function populateYears() < // get this year as a number var date = new Date(); var year = date.getFullYear(); // Make this year, and the 100 years before it available in the year for(var i = 0; i > // when the month or year values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = function() < populateDays(monthSelect.value); >monthSelect.onchange = function() < populateDays(monthSelect.value); >//preserve day selection var previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = function()

Specifications

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 20 12 No support [1] No support 10.62 No support [2]
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) ? 10.62 5
[1] This feature is implemented behind the preference dom.forms.datetime since Gecko 51 (Firefox 51 / Thunderbird 51 / SeaMonkey 2.48), defaulting to false . Since Gecko 55 it is enabled by default on Firefox Nightly (see bug 1366188). See also bug 888320 and TPE DOM/Date time input types. [2] It is recognized but there is no UI.

See also

Источник

Оцените статью