aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/html/element/input/number/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/ru/web/html/element/input/number/index.html')
-rw-r--r--files/ru/web/html/element/input/number/index.html420
1 files changed, 420 insertions, 0 deletions
diff --git a/files/ru/web/html/element/input/number/index.html b/files/ru/web/html/element/input/number/index.html
new file mode 100644
index 0000000000..93f1fb2525
--- /dev/null
+++ b/files/ru/web/html/element/input/number/index.html
@@ -0,0 +1,420 @@
+---
+title: <input type="number">
+slug: Web/HTML/Element/Input/number
+translation_of: Web/HTML/Element/input/number
+---
+<div>{{HTMLRef}}</div>
+
+<p><span class="seoSummary">{{HTMLElement("input")}} элементы типа <strong><code>number</code></strong> используются для того, чтобы дать возможность пользователю ввести число. У них есть встроенная валидация, запрещающая вводить нечисловые значения.</span> Браузер может предоставить возможность увеличить или уменьшить значение специальными стрелками, используя мышь или просто двигая пальцем по экрану.</p>
+
+<div>{{EmbedInteractiveExample("pages/tabbed/input-number.html", "tabbed-shorter")}}</div>
+
+
+
+<p>В браузерах, которые не поддерживают тип <code>number</code>, тип <code>number</code> приводится к <code>text</code>.</p>
+
+<table class="properties">
+ <tbody>
+ <tr>
+ <td><strong>{{anch("Value")}}</strong></td>
+ <td>A {{jsxref("Number")}} representing a number, or empty</td>
+ </tr>
+ <tr>
+ <td><strong>Events</strong></td>
+ <td>{{event("change")}} and {{event("input")}}</td>
+ </tr>
+ <tr>
+ <td><strong>Supported Common Attributes</strong></td>
+ <td>{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("readonly", "input")}}</td>
+ </tr>
+ <tr>
+ <td><strong>IDL attributes</strong></td>
+ <td><code>list</code>, <code>value</code>, <code>valueAsNumber</code></td>
+ </tr>
+ <tr>
+ <td><strong>Methods</strong></td>
+ <td>{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Value">Value</h2>
+
+<p>{{jsxref("Number")}}, представляющий значение введенного числа. Вы можете установить значение по умолчанию, вставив значение в атрибут {{htmlattrxref("value", "input")}}, например:</p>
+
+<pre class="brush: html notranslate">&lt;input id="number" type="number" value="42"&gt;</pre>
+
+<p>{{EmbedLiveSample('Value', 600, 40)}}</p>
+
+<h2 id="Additional_attributes">Additional attributes</h2>
+
+<p>In addition to the attributes commonly supported by all {{HTMLElement("input")}} types, inputs of type <code>number</code> support these attributes:</p>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Attribute</th>
+ <th scope="col">Description</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>{{anch("max")}}</code></td>
+ <td>The maximum value to accept for this input</td>
+ </tr>
+ <tr>
+ <td><code>{{anch("min")}}</code></td>
+ <td>The minimum value to accept for this input</td>
+ </tr>
+ <tr>
+ <td><code>{{anch("placeholder")}}</code></td>
+ <td>An example value to display inside the field when it's empty</td>
+ </tr>
+ <tr>
+ <td><code>{{anch("readonly")}}</code></td>
+ <td>A Boolean attribute controlling whether or not the value is read-only</td>
+ </tr>
+ <tr>
+ <td><code>{{anch("step")}}</code></td>
+ <td>A stepping interval to use when using up and down arrows to adjust the value, as well as for validation</td>
+ </tr>
+ </tbody>
+</table>
+
+<h3 id="htmlattrdefmax">{{htmlattrdef("max")}}</h3>
+
+<p>The maximum value to accept for this input. If the {{htmlattrxref("value", "input")}} entered into the element exceeds this, the element fails <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">constraint validation</a>. If the value of the <code>max</code> attribute isn't a number, then the element has no maximum value.</p>
+
+<p>This value must be greater than or equal to the value of the <code>min</code> attribute.</p>
+
+<h3 id="htmlattrdefmin">{{htmlattrdef("min")}}</h3>
+
+<p>The minimum value to accept for this input. If the {{htmlattrxref("value", "input")}} of the element is less than this, the element fails <a href="/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">constraint validation</a>. If a value is specified for <code>min</code> that isn't a valid number, the input has no minimum value.</p>
+
+<p>This value must be less than or equal to the value of the <code>max</code> attribute.</p>
+
+<p>{{page("/en-US/docs/Web/HTML/Element/input/text", "placeholder", 0, 1, 2)}}</p>
+
+<p>{{page("/en-US/docs/Web/HTML/Element/input/text", "readonly", 0, 1, 2)}}</p>
+
+<h3 id="htmlattrdefstep">{{htmlattrdef("step")}}</h3>
+
+<div id="step-include">
+<p>Атрибут <code>step</code> – это число, которое определяет точность, с которой задаётся значение, или специальное значение <code>any</code>, описанное ниже. Только значения, кратные шагу (<code>{{anch("min")}}</code>, если задано, иначе {{htmlattrxref("value", "input")}}, или подходящее стандартное значение, если ни одно из двух не задано) будут корректными.</p>
+
+<p>Строковое значение <code>any</code> означает, что никакое значение шага не задано и допустимо любое значение (в пределах других ограничений, таких как <code>{{anch("min")}}</code> и <code>{{anch("max")}}</code>).</p>
+
+<div class="note">
+<p><strong>Примечание:</strong> Когда значение, введённое пользователем, не подходит под заданное значение шага, {{Glossary("user agent")}} может округлить его до ближайшего допустимого значения с приоритетом в большую сторону в том случае, если значение находится ровно посередине шага.</p>
+</div>
+</div>
+
+<p>Стандартное значение шага для поля ввода <code>number</code> – это <code>1</code>, что позволяет вводить только целые числа, <em>если</em> только не задать значение шага нецелым числом.</p>
+
+<h2 id="Using_number_inputs">Using number inputs</h2>
+
+<p><code>&lt;input type="number"&gt;</code> elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper <code>type</code> value, <code>number</code>, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down.</p>
+
+<div class="warning">
+<p><strong>Important</strong>: Bear in mind that logically you should not be able to enter characters inside a number of input other than numbers. There seems to be some disagreement about this among browsers; see {{bug(1398528)}}.</p>
+</div>
+
+<div class="note">
+<p><strong>Note</strong>: It's crucial to remember that a user can tinker with your HTML behind the scenes, so your site <em>must not</em> use simple client-side validation for any security purposes. You <em>must</em> verify on the server side any transaction in which the provided value may have any security implications of any kind.</p>
+</div>
+
+<p>Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. The following screenshot is taken from Firefox for Android:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14963/number-keyboard-fxa.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p>
+
+<h3 id="A_simple_number_input">A simple number input</h3>
+
+<p>In its most basic form, a number input can be implemented like this:</p>
+
+<pre class="brush: html notranslate">&lt;label for="ticketNum"&gt;Number of tickets you would like to buy:&lt;/label&gt;
+&lt;input id="ticketNum" type="number" name="ticketNum" value="0"&gt;</pre>
+
+<p>{{EmbedLiveSample('A_simple_number_input', 600, 40)}}</p>
+
+<p>A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the {{htmlattrxref("required", "input")}} attribute is used, the input is no longer considered valid when empty.</p>
+
+<div class="note">
+<p><strong>Note</strong>: Any number is an acceptable value, as long as it is a <a href="https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number">valid floating point number</a> (i.e. not <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity">Infinity</a>).</p>
+</div>
+
+<h3 id="Placeholders">Placeholders</h3>
+
+<p>Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each {{HTMLElement("input")}}. This is where <strong>placeholders</strong> come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take <code>value</code>. It is displayed inside the edit box when the element's <code>value</code> is <code>""</code>. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.</p>
+
+<p>Here, we have an <code>number</code> input with the placeholder <code>"Multiple of 10"</code>. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.</p>
+
+<pre class="brush: html notranslate">&lt;input type="number" placeholder="Multiple of 10"&gt;</pre>
+
+<p>{{EmbedLiveSample('Placeholders', 600, 40)}}</p>
+
+<h3 id="Controlling_step_size">Controlling step size</h3>
+
+<p>By default, the up and down buttons provided for you to step the number up and down will step the value up and down by 1. You can change this by providing a {{htmlattrxref("step", "input")}} attribute, which takes as its value a number specifying the step amount. Our above example contains a placeholder saying that the value should be a multiple of 10, so it makes sense to add a <code>step</code> value of 10:</p>
+
+<pre class="brush: html notranslate">&lt;input type="number" placeholder="multiple of 10" step="10"&gt;</pre>
+
+<p>{{EmbedLiveSample('Controlling_step_size', 600, 40)}}</p>
+
+<p>In this example you should find that the up and down step arrows will increase and decrease the value by 10 each time, not 1. You can still manually enter a number that's not a multiple of 10, but it will be considered invalid.</p>
+
+<h3 id="Specifying_minimum_and_maximum_values">Specifying minimum and maximum values</h3>
+
+<p>You can use the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of 0, and a maximum of 100:</p>
+
+<pre class="brush: html notranslate">&lt;input type="number" placeholder="multiple of 10" step="10" min="0" max="100"&gt;</pre>
+
+<p>{{EmbedLiveSample('Specifying_minimum_and_maximum_values', 600, 40)}}</p>
+
+<p>In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid.</p>
+
+<h3 id="Allowing_decimal_values">Allowing decimal values</h3>
+
+<p>One issue with number inputs is that their step size is 1 by default — if you try to enter a number with a decimal, such as "1.0", it will be considered invalid. If you want to enter a value that requires decimals, you'll need to reflect this in the <code>step</code> value (e.g. <code>step="0.01"</code> to allow decimals to two decimal places). Here's a simple example:</p>
+
+<pre class="brush: html notranslate">&lt;input type="number" placeholder="1.0" step="0.01" min="0" max="10"&gt;</pre>
+
+<p>{{EmbedLiveSample("Allowing_decimal_values", 600, 40)}}</p>
+
+<p>See that this example allows any value between 0.0 and 10.0, with decimals to two places. "9.52" is valid, but "9.521" is not, for example.</p>
+
+<h3 id="Controlling_input_size">Controlling input size</h3>
+
+<p>{{HTMLElement("input")}} elements of type <code>number</code> don't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to <a href="/en-US/docs/Web/CSS">CSS</a> to change the size of these controls.</p>
+
+<p>For example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our HTML to include an ID and to shorten our placeholder since the field will be too narrow for the text we have been using so far:</p>
+
+<pre class="brush: html notranslate">&lt;input type="number" placeholder="x10" step="10" min="0" max="100" id="number"&gt;</pre>
+
+<p>Then we add some CSS to narrow the width of the element with the ID <code>number</code>:</p>
+
+<pre class="brush: css notranslate">#number {
+ width: 3em;
+}</pre>
+
+<p>The result looks like this:</p>
+
+<p>{{EmbedLiveSample('Controlling_input_size', 600, 40)}}</p>
+
+<h3 id="Offering_suggested_values">Offering suggested values</h3>
+
+<p>You can provide a list of default options from which the user can select by specifying the {{htmlattrxref("list", "input")}} attribute, which contains as its value the ID of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value; each <code>option</code>'s <code>value</code> is the corresponding suggested value for the number entry box.</p>
+
+<pre class="brush: html notranslate">&lt;input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers"&gt;
+&lt;span class="validity"&gt;&lt;/span&gt;
+
+&lt;datalist id="defaultNumbers"&gt;
+ &lt;option value="10045678"&gt;
+ &lt;option value="103421"&gt;
+ &lt;option value="11111111"&gt;
+ &lt;option value="12345678"&gt;
+ &lt;option value="12999922"&gt;
+&lt;/datalist&gt;</pre>
+
+<p>{{EmbedLiveSample("Offering_suggested_values", 600, 40)}}</p>
+
+<div class="note">
+<p>Use of the {{htmlattrxref("list", "input")}} attribute with <code>number</code> inputs is not supported in all browsers. It works in Chrome and Opera, for example, but not in Firefox.</p>
+</div>
+
+<h2 id="Validation">Validation</h2>
+
+<p>We have already mentioned a number of validation features of <code>number</code> inputs, but let's review them now:</p>
+
+<ul>
+ <li><code>&lt;input type="number"&gt;</code> elements automatically invalidate any entry that isn't a number (or empty, unless <code>required</code> is specified).</li>
+ <li>You can use the {{htmlattrxref("required", "input")}} attribute to make an empty entry invalid, i.e. the input has to be filled in.</li>
+ <li>You can use the {{htmlattrxref("step", "input")}} attribute to constrain valid values to a certain set of steps (e.g. multiples of 10).</li>
+ <li>You can use the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes to constrain valid values to lower and upper bounds.</li>
+</ul>
+
+<p>The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons when the input value is valid/invalid:</p>
+
+<pre class="brush: html notranslate">&lt;form&gt;
+ &lt;div&gt;
+ &lt;label for="balloons"&gt;Number of balloons to order (multiples of 10):&lt;/label&gt;
+ &lt;input id="balloons" type="number" name="balloons" step="10" min="0" max="100" required&gt;
+ &lt;span class="validity"&gt;&lt;/span&gt;
+ &lt;/div&gt;
+ &lt;div&gt;
+ &lt;input type="submit"&gt;
+ &lt;/div&gt;
+&lt;/form&gt;</pre>
+
+<p>{{EmbedLiveSample("Validation", 600, 80)}}</p>
+
+<p>Try submitting the form with different invalid values entered — e.g. no value, a value below 0 or above 100, a value that is not a multiple of 10, or a non-numerical value — and see how the error messages the browser gives you differ with different ones.</p>
+
+<p>The CSS applied to this example is as follows:</p>
+
+<pre class="brush: css notranslate">div {
+ margin-bottom: 10px;
+}
+
+input:invalid+span:after {
+ content: '✖';
+ padding-left: 5px;
+}
+
+input:valid+span:after {
+ content: '✓';
+ padding-left: 5px;
+}</pre>
+
+<p>Here we use the {{cssxref(":invalid")}} and {{cssxref(":valid")}} pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent {{htmlelement("span")}} element, indicating if the current value is valid. We put it on a separate <code>&lt;span&gt;</code> element for added flexibility; some browsers don't display generated content very effectively on some types of form inputs (read for example the section on <a href="/en-US/docs/Web/HTML/Element/input/date#Validation"><code>&lt;input type="date"&gt;</code> validation</a>).</p>
+
+<div class="warning">
+<p><strong>Important</strong>: HTML form validation is <em>not</em> a substitute for server-side 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 bypass your HTML 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).</p>
+</div>
+
+<h3 id="Pattern_validation">Pattern validation</h3>
+
+<p><code>&lt;input type="number"&gt;</code> elements do not support use of the {{htmlattrxref("pattern", "input")}} attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes, as explained above.</p>
+
+<h2 id="Examples">Examples</h2>
+
+<p>We've already covered the fact that by default, the increment is 1, and you can use the {{htmlattrxref("step", "input")}} attribute to allow decimal inputs. Let's take a closer look. In the following example we've set up a form for entering the user's height; it defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places.</p>
+
+<p>{{EmbedLiveSample("Examples", 600, 100)}}</p>
+
+<p>The HTML looks like this:</p>
+
+<pre class="brush: html notranslate">&lt;form&gt;
+ &lt;div class="metersInputGroup"&gt;
+ &lt;label for="meters"&gt;Enter your height — meters:&lt;/label&gt;
+ &lt;input id="meters" type="number" name="meters" step="0.01" min="0" placeholder="e.g. 1.78" required&gt;
+ &lt;span class="validity"&gt;&lt;/span&gt;
+ &lt;/div&gt;
+ &lt;div class="feetInputGroup" style="display: none;"&gt;
+ &lt;span&gt;Enter your height — &lt;/span&gt;
+ &lt;label for="feet"&gt;feet:&lt;/label&gt;
+ &lt;input id="feet" type="number" name="feet" min="0" step="1"&gt;
+ &lt;span class="validity"&gt;&lt;/span&gt;
+ &lt;label for="inches"&gt;inches:&lt;/label&gt;
+ &lt;input id="inches" type="number" name="inches" min="0" max="11" step="1"&gt;
+ &lt;span class="validity"&gt;&lt;/span&gt;
+ &lt;/div&gt;
+ &lt;div&gt;
+ &lt;input type="button" class="meters" value="Enter height in feet and inches"&gt;
+ &lt;/div&gt;
+ &lt;div&gt;
+ &lt;input type="submit" value="Submit form"&gt;
+ &lt;/div&gt;
+&lt;/form&gt;</pre>
+
+<p>You'll see that we are using many of the attributes we've already looked at in the article earlier on. Since we want to accept a meter value in centimeters, we've set the <code>step</code> value to <code>0.01</code>, so that values like 1.78 are not seen as invalid. We've also provided a placeholder for that input.</p>
+
+<p>We've hidden the feet and inches inputs initially using <code>style="display: none;"</code> so that meters is the default entry type.</p>
+
+<p>Now on to the CSS — this looks very similar to the validation styling we saw before; nothing remarkable here:</p>
+
+<pre class="brush: css notranslate">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;
+}</pre>
+
+<p>And finally, the JavaScript:</p>
+
+<pre class="brush: js notranslate">var metersInputGroup = document.querySelector('.metersInputGroup');
+var feetInputGroup = document.querySelector('.feetInputGroup');
+var metersInput = document.querySelector('#meters');
+var feetInput = document.querySelector('#feet');
+var inchesInput = document.querySelector('#inches');
+var switchBtn = document.querySelector('input[type="button"]');
+
+switchBtn.addEventListener('click', function() {
+ if(switchBtn.getAttribute('class') === 'meters') {
+ switchBtn.setAttribute('class', 'feet');
+ switchBtn.value = 'Enter height in meters';
+
+ metersInputGroup.style.display = 'none';
+ feetInputGroup.style.display = 'block';
+
+ feetInput.setAttribute('required', '');
+ inchesInput.setAttribute('required', '');
+ metersInput.removeAttribute('required');
+
+ metersInput.value = '';
+ } else {
+ switchBtn.setAttribute('class', 'meters');
+ switchBtn.value = 'Enter height in feet and inches';
+
+ metersInputGroup.style.display = 'block';
+ feetInputGroup.style.display = 'none';
+
+ feetInput.removeAttribute('required');
+ inchesInput.removeAttribute('required');
+ metersInput.setAttribute('required', '');
+
+ feetInput.value = '';
+ inchesInput.value = '';
+ }
+});</pre>
+
+<p>After declaring a few variables, we add an event listener to the button to control the switching mechanism. This is pretty simple, mostly involving changing over the button class and label, and updating the display values of the two sets of inputs when the button is pressed. Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.</p>
+
+<div class="note">
+<p>Note that when the user clicks the button, we remove the <code>required</code> attribute(s) from the input(s) we are hiding, and empty the <code>value</code> attribute(s). This is so that we can submit the form if both input sets aren't filled in, and won't submit data that we didn't mean to submit. If we didn't do this, you'd have to fill in both feet/inches <strong>and</strong> meters to submit the form!</p>
+</div>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>{{SpecName('HTML WHATWG', 'forms.html#number-state-(type=number)', '&lt;input type="number"&gt;')}}</td>
+ <td>{{Spec2('HTML WHATWG')}}</td>
+ <td>Initial definition</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('HTML5.1', 'sec-forms.html#number-state-typenumber', '&lt;input type="number"&gt;')}}</td>
+ <td>{{Spec2('HTML5.1')}}</td>
+ <td>Initial definition</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+
+
+<p>{{Compat("html.elements.input.input-number")}}</p>
+
+<h2 id="See_also">See also</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/HTML/Forms">HTML forms guide</a></li>
+ <li>{{HTMLElement("input")}}</li>
+ <li><code><a href="/en-US/docs/Web/HTML/Element/input/tel">&lt;input type="tel"&gt;</a></code></li>
+</ul>