Html button type button action

Html button type button action

An elements’ value attribute contains a string that is used as the button’s label.

input type="button" value="Click Me" /> 

Button without a value

If you don’t specify a value , you get an empty button:

Using buttons

A simple button

We’ll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph):

form> input type="button" value="Start machine" /> form> p>The machine is stopped.p> 
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton()  if (button.value === "Start machine")  button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else  button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > > 

The script gets a reference to the HTMLInputElement object representing the in the DOM, saving this reference in the variable button . addEventListener() is then used to establish a function that will be run when click events occur on the button.

Adding keyboard shortcuts to buttons

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the accesskey global attribute.

In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).

form> input type="button" value="Start machine" accesskey="s" /> form> p>The machine is stopped.p> 
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton()  if (button.value === "Start machine")  button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else  button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > > 

Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).

Disabling and enabling a button

To disable a button, specify the disabled global attribute on it, like so:

input type="button" value="Disable me" disabled /> 

Setting the disabled attribute

You can enable and disable buttons at run time by setting disabled to true or false . In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true . A setTimeout() function is then used to reset the button back to its enabled state after two seconds.

input type="button" value="Enabled" /> 
const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton()  button.disabled = true; button.value = "Disabled"; setTimeout(() =>  button.disabled = false; button.value = "Enabled"; >, 2000); > 

Inheriting the disabled state

If the disabled attribute isn’t specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting disabled on the container.

The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.

fieldset> legend>Button grouplegend> input type="button" value="Button 1" /> input type="button" value="Button 2" /> input type="button" value="Button 3" /> fieldset> 
const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton()  fieldset.disabled = true; setTimeout(() =>  fieldset.disabled = false; >, 2000); > 

Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the autocomplete attribute to control this feature.

Validation

Buttons don’t participate in constraint validation; they have no real value to be constrained.

Examples

div class="toolbar"> input type="color" aria-label="select pen color" /> input type="range" min="2" max="50" value="30" aria-label="select pen size" />span class="output">30span> input type="button" value="Clear canvas" /> div> canvas class="myCanvas"> p>Add suitable fallback here.p> canvas> 
body  background: #ccc; margin: 0; overflow: hidden; > .toolbar  background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"]  width: 90%; margin: 0 auto; display: block; > input[type="range"]  width: 70%; > span  position: relative; bottom: 5px; > 
const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees)  return (degrees * Math.PI) / 180; > // update sizepicker output value sizePicker.oninput = () =>  output.textContent = sizePicker.value; >; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) =>  curX = e.pageX; curY = e.pageY; >; canvas.onmousedown = () =>  pressed = true; >; canvas.onmouseup = () =>  pressed = false; >; clearBtn.onclick = () =>  ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); >; function draw()  if (pressed)  ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); > requestAnimationFrame(draw); > draw(); 

Technical summary

Specifications

Источник

Html button type button action

Тег (от англ. button — кнопка) создаёт на веб-странице кнопки и по своему действию напоминает результат, получаемый с помощью (с атрибутом type=»button | reset | submit» ).

В отличие от этого элемента, предлагает расширенные возможности по созданию кнопок. Например, на подобной кнопке можно размещать любые элементы HTML, в том числе изображения. Используя стили можно определить вид кнопки путём изменения шрифта, цвета фона, размеров и других параметров.

Синтаксис¶

Закрывающий тег обязателен.

Атрибуты¶

autofocus Устанавливает, что кнопка получает фокус после загрузки страницы. disabled Блокирует доступ и изменение элемента. form Связывает между собой форму и кнопку. formaction Задаёт адрес, на который пересылаются данные формы при нажатии на кнопку. formenctype Способ кодирования данных формы. formmethod Указывает метод пересылки данных формы. formnovalidate Отменяет проверку формы на корректность. formtarget Открывает результат отправки формы в новом окне или фрейме. name Определяет уникальное имя кнопки. type Устанавливает тип кнопки: обычная; для отправки данных формы на сервер; для очистки формы. value Значение кнопки, которое будет отправлено на сервер или прочитано с помощью скриптов.

Также для этого тега доступны универсальные атрибуты.

autofocus¶

Атрибут autofocus устанавливает, что кнопка получает фокус после загрузки страницы. Такую кнопку можно нажать сразу без перевода на неё фокуса, например, с помощью клавиатуры.

Значение по умолчанию

По умолчанию это значение выключено.

disabled¶

Блокирует доступ к кнопке и её изменение. Она в таком случае отображается серым цветом и недоступна для активации пользователем. Кроме того, такая кнопка не может получить фокус путём нажатия на клавишу Tab , мышью или другим способом. Тем не менее, такое состояние кнопки можно изменять через скрипты. Значение блокированной кнопки не передаётся на сервер.

Значение по умолчанию

По умолчанию это значение выключено.

form¶

Связывает кнопку с формой по её идентификатору. Такая связь необходима в случае, когда кнопка не располагается внутри элемента , например, при создании её программно.

Идентификатор формы (значение атрибута id элемента ).

Значение по умолчанию

formaction¶

Определяет адрес обработчика формы — это программа, которая получает данные формы и производит с ними желаемые действия. Атрибут formaction по своему действию аналогичен атрибуту action элемента . Если одновременно указать action и formaction , то при нажатии на кнопку атрибут action игнорируется и данные пересылаются по адресу, указанному в formaction .

formenctype¶

Устанавливает способ кодирования данных формы при их отправке на сервер. Обычно явно указывается в случае, когда используется поле для отправки файла ( input type=»file» ). Этот атрибут по своему действию аналогичен атрибуту enctype элемента .

button formenctype="application/x-www-form-urlencoded | multipart/form-data | text/plain" > . button> 

application/x-www-form-urlencoded Вместо пробелов ставится + , символы вроде русских букв кодируются их шестнадцатеричными значениями (например, %D0%9F%D0%B5%D1%82%D1%8F вместо Петя). multipart/form-data Данные не кодируются. Это значение применяется при отправке файлов. text/plain Пробелы заменяются знаком + , буквы и другие символы не кодируются.

Значение по умолчанию

formmethod¶

Атрибут сообщает браузеру, каким методом следует передавать данные формы на сервер.

button formmethod="get | post">. button> 

Различают два метода — GET и POST.

GET Этот метод предназначен для передачи данных формы непосредственно в адресной строке в виде пар « имя=значение », которые добавляются к адресу страницы после вопросительного знака и разделяются между собой амперсандом (символ & ). Полный адрес к примеру будет http://site.ru/doc/?name=Vasya&password=pup . Объём данных в методе ограничен 4 Кб. POST Посылает на сервер данные в запросе браузера, объём пересылаемых данных ограничен лишь настройками сервера.

formnovalidate¶

Отменяет встроенную проверку данных введённых пользователем в форме на корректность при нажатии на кнопку. Такая проверка делается браузером автоматически при отправке формы на сервер для полей , , а также при наличии атрибута pattern или required у элемента .

button formnovalidate>. button> 

Значение по умолчанию

По умолчанию этот атрибут выключен.

formtarget¶

Определяет имя фрейма, в которое будет загружаться результат, возвращаемый обработчиком формы, в виде HTML-документа.

button formtarget=" | _blank | _self | _parent | _top" > . button> 

_blank Загружает страницу в новую вкладку браузера. _self Загружает страницу в текущую вкладку. _parent Загружает страницу во фрейм-родитель; если фреймов нет, то это значение работает как _self . _top Отменяет все фреймы и загружает страницу в полном окне браузера; если фреймов нет, то это значение работает как _self .

name¶

Определяет уникальное имя кнопки. Как правило, это имя используется при отправке значения кнопки на сервер или для доступа к кнопке через скрипты.

В качестве имени используется набор символов, включая числа и буквы. JavaScript чувствителен к регистру, поэтому при обращении к элементу по имени соблюдайте ту же форму написания, что и в атрибуте name .

Значение по умолчанию

type¶

Определяет тип кнопки, который устанавливает её поведение в форме. По внешнему виду кнопки разного типа никак не различаются, но у каждой такой кнопки свои функции.

button type="button | reset | submit">. button> 

button Обычная кнопка. reset Кнопка для очистки введённых данных формы и возвращения значений в первоначальное состояние. submit Кнопка для отправки данных формы на сервер. menu Открывает меню, созданное с помощью элемента .

Значение по умолчанию

value¶

Определяет значение кнопки, которое будет отправлено на сервер. На сервер отправляется пара « имя=значение », где имя задаётся атрибутом name элемента , а значение — атрибутом value . Значение может как совпадать с текстом на кнопке, так быть и самостоятельным. Также атрибут value применяется для доступа к данным через скрипты.

Значение по умолчанию

Спецификации¶

Описание и примеры¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 html> head> meta charset="utf-8" /> title>BUTTONtitle> head> body> p style="text-align: center"> button>Кнопка с текстомbutton> button> img src="image/umbrella.gif" alt="Зонтик" style="vertical-align: middle" /> Кнопка с рисунком button> p> body> html> 

Источник

Читайте также:  Slider bar css style
Оцените статью