<input> elements of type week create input fields allowing easy entry of a year plus the ISO 8601 week number during that year (i.e., week 1 to 52 or 53 ).

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

The control's user interface varies from browser to browser; cross-browser support is currently a bit limited, with only Chrome/Opera and Microsoft Edge supporting it at this time. In non-supporting browsers, the control degrades gracefully to function identically to <input type="text"> .

In Chrome/Opera the week control provides slots to fill in week and year values, a pop-up calendar interface to select them more visually, and an "X" button to clear the control's value.

The Edge week control is somewhat more elaborate, opening up week and year pickers with sliding reels.

A DOMString representing a week and year, or empty
事件 change and input
Supported common attributes autocomplete , list , readonly ,和 step
IDL attributes value , valueAsDate , valueAsNumber ,和 list .
方法 select() , stepDown() ,和 stepUp()

A DOMString representing the value of the week/year entered into the input. The format of the date and time value used by this input type is described in Format of a valid week string in 用于 HTML 的日期和时间格式 .

You can set a default value for the input by including a value inside the value attribute, like so:

<label for="week">What week would you like to start?</label>
<input id="week" type="week" name="week" value="2017-W01">

One thing to note is that the displayed format may differ from the actual value , which is always formatted yyyy-Www . When the above value is submitted to the server, for example, browsers may display it as Week 01, 2017 , but the submitted value will always look like week=2017-W01 .

You can also get and set the value in JavaScript using the input element's value 特性,例如:

var weekControl = document.querySelector('input[type="week"]');
weekControl.value = '2017-W45';

Additional attributes

In addition to the attributes common to <input> elements, week inputs offer the following attributes:

属性 描述
max The latest year and week to accept as valid input
min The earliest year and week to accept as valid input
readonly A Boolean which, if present, indicates that the user cannot edit the field's contents
step The stepping interval (the distance between allowed values) to use for both user interface and constraint validation

max

The latest (time-wise) year and week number, in the string format discussed in the section above, to accept. If the value entered into the element exceeds this, the element fails constraint validation . If the value of the max attribute isn't a valid week string, then the element has no maximum value.

This value must be greater than or equal to the year and week specified by the min 属性。

min

The earliest year and week to accept. If the value of the element is less than this, the element fails constraint validation . If a value is specified for min that isn't a valid week string, the input has no minimum value.

This value must be less than or equal to the value of the max 属性。

readonly

A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement.value 特性。

注意: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

step

step attribute is a number that specifies the granularity that the value must adhere to, or the special value any , which is described below. Only values which are equal to the basis for stepping ( min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.

A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max ).

注意: When the data entered by the user doesn't adhere to the stepping configuration, the 用户代理 may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

For week inputs, the value of step is given in weeks, with a scaling factor of 604,800,000 (since the underlying numeric value is in milliseconds). The default value of step is 1, indicating 1week. The default stepping base is -259,200,000, which is the beginning of the first week of 1970 ( "1970-W01" ).

At this time, it's unclear what a value of "any" means for step when used with week inputs. This will be updated as soon as that information is determined.

Using week inputs

Week inputs sound convenient at first glance, since they provide an easy UI for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale. However, there are issues with <input type="week"> because browser support is not guaranteed across all browsers.

We'll look at basic and more complex uses of <input type="week"> , then offer advice on mitigating the browser support issue later on (see Handling browser support ).

Basic uses of week

The simplest use of <input type="week"> involves a basic <input> and <label> element combination, as seen below:

<form>
  <label for="week">What week would you like to start?</label>
  <input id="week" type="week" name="week">
</form>

Controlling input size

<input type="week"> doesn't support form sizing attributes such as size . You'll have to resort to CSS for sizing needs.

Using the step attribute

You should be able to use the step attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers.

验证

默认情况下, <input type="week"> does not apply any validation to entered values. The UI implementations generally don't let you specify anything that isn't a valid week/year, which is helpful, but it's still possible to submit with the field empty, and you might want to restrict the range of choosable weeks.

Setting maximum and minimum weeks

可以使用 min and max attributes to restrict the valid weeks that can be chosen by the user. In the following example we are setting a minimum value of Week 01, 2017 and a maximum value of Week 52, 2017 :

<form>
  <label for="week">What week would you like to start?</label>
  <input id="week" type="week" name="week"
         min="2017-W01" max="2017-W52">
  <span class="validity"></span>
</form>

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 <span> 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;
  position: relative;
}
input[type="number"] {
  width: 100px;
}
input + span {
  padding-right: 30px;
}
input:invalid+span:after {
  position: absolute;
  content: '✖';
  padding-left: 5px;
}
input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
}

The result here is that only weeks between W01 and W52 in 2017 will be seen as valid and be selectable in supporting browsers.

Making week values required

In addition you can use the required attribute to make filling in the week mandatory. As a result, supporting browsers will display an error if you try to submit an empty week field.

Let's look at an example; here we've set minimum and maximum weeks, and also made the field required:

<form>
  <div>
    <label for="week">What week would you like to start?</label>
    <input id="week" type="week" name="week"
         min="2017-W01" max="2017-W52" required>
    <span class="validity"></span>
  </div>
  <div>
      <input type="submit" value="Submit form">
  </div>
</form>

If you try to submit the form with no value, 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:

重要 : 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, of the wrong type, and so forth).

Handling browser support

As mentioned above, the major problem with using week inputs right now is browser support: Safari and Firefox don't support it on desktop, and old versions of IE don't support it.

Mobile platforms such as Android and iOS make really good use of such input types, providing specialist UI controls that make it really easy to select values in a touchscreen environment. For example, the week picker on Chrome 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 more serious. As mentioned earlier, with a week input the actual value is always normalized to the format yyyy-Www . When the browser falls back to a generic text input, there's nothing to guide the user toward correctly formatting the input (and it's certainly not intuitive). There are multiple ways in which people could write week values; for example:

  • Week 1 2017
  • Jan 2-8 2017
  • 2017-W01
  • etc.

The best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls ( <select> elements being popular; see below for an example), or use JavaScript libraries such as jQuery date picker .

范例

In this example we create two sets of UI elements for choosing weeks: a native picker created using <input type="week"> , and a set of two <select> elements for choosing weeks/years in older browsers that don't support the week input type.

The HTML looks like so:

<form>
  <div class="nativeWeekPicker">
    <label for="week">What week would you like to start?</label>
    <input id="week" type="week" name="week"
           min="2017-W01" max="2018-W52" required>
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">What week would you like to start?</p>
  <div class="fallbackWeekPicker">
    <div>
      <span>
        <label for="week">Week:</label>
        <select id="fallbackWeek" name="week">
        </select>
      </span>
      <span>
        <label for="year">Year:</label>
        <select id="year" name="year">
          <option value="2017" selected>2017</option>
          <option value="2018">2018</option>
        </select>
      </span>
    </div>
  </div>
</form>

The week values are dynamically generated by the JavaScript code below.

div {
  margin-bottom: 10px;
  position: relative;
}
input[type="number"] {
  width: 100px;
}
input + span {
  padding-right: 30px;
}
input:invalid+span:after {
  position: absolute;
  content: '✖';
  padding-left: 5px;
}
input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
}

The other part of the code that may be of interest is the feature detection code. To detect whether the browser supports <input type="week"> , we create a new <input> element, try setting its type to week , then immediately check what its type is set to. Non-supporting browsers will return text , because the week type falls back to type text 。若 <input type="week"> is not supported, we hide the native picker and show the fallback picker UI ( <select> s) instead.

// define variables
var nativePicker = document.querySelector('.nativeWeekPicker');
var fallbackPicker = document.querySelector('.fallbackWeekPicker');
var fallbackLabel = document.querySelector('.fallbackLabel');
var yearSelect = document.querySelector('#year');
var weekSelect = document.querySelector('#fallbackWeek');
// 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');
try {
  test.type = 'week';
} catch (e) {
  console.log(e.description);
}
// 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 weeks dynamically
  populateWeeks();
}
function populateWeeks() {
  // Populate the week select with 52 weeks
  for(var i = 1; i <= 52; i++) {
    var option = document.createElement('option');
    option.textContent = (i < 10) ? ("0" + i) : i;
    weekSelect.appendChild(option);
  }
}

注意 : Remember that some years have 53 weeks in them (see Weeks per year )! You'll need to take this into consideration when developing production apps.

规范

规范 状态 注释
HTML 实时标准
The definition of '<input type="week">' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
type="week" Chrome 完整支持 20 Edge 完整支持 12 Firefox 不支持 No 注意事项
不支持 No 注意事项
注意事项 bug 888320 .
IE 不支持 No Opera 完整支持 11 Safari 不支持 No 注意事项
不支持 No 注意事项
注意事项 bug 200416 .
WebView Android 完整支持 Yes Chrome Android 完整支持 Yes Firefox Android 完整支持 Yes Opera Android 完整支持 Yes Safari iOS 完整支持 Yes Samsung Internet Android 完整支持 Yes

图例

完整支持

完整支持

不支持

不支持

见实现注意事项。

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. <input> 类型
    1. <input type="button">
    2. <input type="checkbox">
    3. <input type="color">
    4. <input type="date">
    5. <input type="datetime">
    6. <input type="datetime-local">
    7. <input type="email">
    8. <input type="file">
    9. <input type="hidden">
    10. <input type="image">
    11. <input type="month">
    12. <input type="number">
    13. <input type="password">
    14. <input type="radio">
    15. <input type="range">
    16. <input type="reset">
    17. <input type="search">
    18. <input type="submit">
    19. <input type="tel">
    20. <input type="text">
    21. <input type="time">
    22. <input type="url">
    23. <input type="week">
  2. HTML 元素
    1. A
      1. <a>
      2. <abbr>
      3. <acronym>
      4. <address>
      5. <applet>
      6. <area>
      7. <article>
      8. <aside>
      9. <audio>
    2. B
      1. <b>
      2. <base>
      3. <basefont>
      4. <bdi>
      5. <bdo>
      6. <bgsound>
      7. <big>
      8. <blink>
      9. <blockquote>
      10. <body>
      11. <br>
      12. <button>
    3. C
      1. <canvas>
      2. <caption>
      3. <center>
      4. <cite>
      5. <code>
      6. <col>
      7. <colgroup>
      8. <content>
    4. D
      1. <data>
      2. <datalist>
      3. <dd>
      4. <del>
      5. <details>
      6. <dfn>
      7. <dialog>
      8. <dir>
      9. <div>
      10. <dl>
      11. <dt>
    5. E
      1. <em>
      2. <embed>
    6. F
      1. <fieldset>
      2. <figcaption>
      3. <figure>
      4. <font>
      5. <footer>
      6. <form>
      7. <frame>
      8. <frameset>
    7. G H
      1. <h1>
      2. <h2>
      3. <h3>
      4. <h4>
      5. <h5>
      6. <h6>
      7. <head>
      8. <header>
      9. <hgroup>
      10. <hr>
      11. <html>
    8. I
      1. <i>
      2. <iframe>
      3. <img>
      4. <input>
      5. <ins>
      6. <isindex>
    9. J K
      1. <kbd>
      2. <keygen>
    10. L
      1. <label>
      2. <legend>
      3. <li>
      4. <link>
      5. <listing>
    11. M
      1. <main>
      2. <map>
      3. <mark>
      4. <marquee>
      5. <menu>
      6. <menuitem>
      7. <meta>
      8. <meter>
    12. N
      1. <nav>
      2. <nobr>
      3. <noframes>
      4. <noscript>
    13. O
      1. <object>
      2. <ol>
      3. <optgroup>
      4. <option>
      5. <output>
    14. P
      1. <p>
      2. <param>
      3. <picture>
      4. <plaintext>
      5. <pre>
      6. <progress>
    15. Q
      1. <q>
    16. R
      1. <rp>
      2. <rt>
      3. <rtc>
      4. <ruby>
    17. S
      1. <s>
      2. <samp>
      3. <script>
      4. <section>
      5. <select>
      6. <shadow>
      7. <slot>
      8. <small>
      9. <source>
      10. <spacer>
      11. <span>
      12. <strike>
      13. <strong>
      14. <style>
      15. <sub>
      16. <summary>
      17. <sup>
    18. T
      1. <table>
      2. <tbody>
      3. <td>
      4. <template>
      5. <textarea>
      6. <tfoot>
      7. <th>
      8. <thead>
      9. <time>
      10. <title>
      11. <tr>
      12. <track>
      13. <tt>
    19. U
      1. <u>
      2. <ul>
    20. V
      1. <var>
      2. <video>
    21. W
      1. <wbr>
    22. X Y Z
      1. <xmp>

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1