<input type="button">
<input> elements of type button are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the click event).
Try it
Note: While <input> elements of type button are still perfectly valid HTML, the newer <button> element is now the favored way to create buttons. Given that a <button> ‘s label text is inserted between the opening and closing tags, you can include HTML in the label, even images.
Value
Button with a value
An <input type=»button»> elements’ value attribute contains a string that is used as the button’s label.
Button without a value
If you don’t specify a value , you get an empty button:
Using buttons
<input type=»button»> elements have no default behavior (their cousins, <input type=»submit»> and <input type=»reset»> are used to submit and reset forms, respectively). To make buttons do anything, you have to write JavaScript code to do the work.
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):
The script gets a reference to the HTMLInputElement object representing the <input> 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 <input> 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).
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:
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.
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 <fieldset> 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 <fieldset> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.
Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> 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
The below example shows a very simple drawing app created using a <canvas> element and some simple CSS and JavaScript (we’ll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas.
Тонкости свойства disable у кнопок формы, отправляемой на сервер (Как делать кнопки неактивными)
Уже неоднократно на хабре (вот в этой публикации и в этой) ставился вопрос о том, что было бы хорошо кнопкам формы, отправляемой на сервер, ставить свойство disabled = "disabled" .
Однако, до сих пор так и не разобрались, зачем это нужно и как все-таки это делать. Казалось бы, что может быть проще и о чем здесь вообще можно разговаривать, ан нет — на поверку все оказалось не так тривиально. Сразу замечу, что нижеследующие рассуждения применимы к обеим типам форм: как отправляемым через обычный SUBMIT, так и с помощью AJAX.
Зачем нужно делать кнопки неактивными
- Чтобы пользователю стало очевидным, что он уже нажал на кнопку, и что форма отправляется
- Чтобы сервер не загружался лишними запросами, и чтобы уменьшить вероятность какой-либо ошибки
Понятно также, что лишние запросы можно предотвратить, повесив на форму какой-нибудь class="form_is_loading" , и при всяком сабмите проверять на наличие этого класса. Но зачем делать эти проверки, когда можно обойтись без них, просто сделав кнопку неактивной?
Как делать кнопки неактивными
Этот предложенный в вышеупомянутых топиках простой вариант оказывается недостаточным и неработоспособным.
How to disable button with CSS
In this blog post, we will look into “How to disable button with CSS” on a webpage & get into various ascpects relating to it.
Contents
How to disable button with CSS?
Buttons are placed on a webpage to perform some event. When the user clicks it then something happens on that page as per the coded actions by the programmer.
There are certain scenarios that we want to show the button but it will only be clickable after a certain condition is fulfilled. Example is the Login page, we want the user to enter the username & password then he can click the login button to enter within the application. When the details are not yet entered by the user then clicking the button is of no use so it can be kept disabled.
After disabling the button, it will stop performing any action & as a default style it will be grayed out. When the user clicks it, the main event will not be performed.
Disabled buttons can also be styled with the help of CSS styles. We can also change the cursor when the user hovers over the button so that the user can easily understand that the button is disabled.
Let’s walk through the code to disable button with CSS :-
Result :-
background-image property specifying the image to be displayed. It futher sets the width & height of the header element.
How to style disabled button with CSS?
It is necessary to style a disabled button in a proper manner so that user can understand it is disabled. If user is unable to understand he will keep clicking the button & will think there something wrong in this website.
Usually the disabled button can be shown as grayed out with a cursor value of not allowed. Different variations of grayed color can be applied as per the preference.
The title text also helps in giving quick information to the user. Title text appears automatically when the user hovers over the button.
The style of the disabled button should be different from the style of the normal buttons. So there can be 2 different set of styles defined in CSS for normal button & disabled button.
Below code is used for styling the disabled buttons :-
Result :-
How to disable hover effect when button is disabled CSS?
When the button hover effect is defined in styles then it gets applied to all the buttons. The button may be enabled or disabled the same style applies to both with no difference.
We can modify this default behavior & apply the style only to the enabled buttons on a web page. For the disabled buttons this style of hover effect will not be applied.
Changing the hover effect is necessary for disabled buttons because the users always hover the buttons before clicking it. If the hover effect for disabled button is the same as the enabled button then there will be no difference & disabled button might look like an enabled button.
The style for the disabled button is usually faint. So the hover effect can also be styled to the same pattern to maintain consistency.
Атрибут disabled
Атрибут disabled блокирует элемент HTML формы, то есть делает его неактивным. Является атрибутом без значения.
Блокировка элементов обычно нужна для того, чтобы запретить пользователю менять некоторые значения (которые, тем не менее, должны быть показаны пользователю в виде элементов формы). Иногда элементы блокируют (и снимают блокировку) с помощью JavaSctipt.
Поведение
В случае кнопки ( button или input с атрибутом type в значениях button , reset или submit ) блокировка означает, что на кнопку нельзя будет нажать. В случае с текстовым полем ввода ( input или textarea ) в нем нельзя будет поменять или скопировать текст. В случае с чекбоксами и радио их состояние (отмечено или нет) нельзя будет сменить. В случае с выпадающими списками select нельзя будет сменить выбранный пункт списка.
Заблокированный элемент по умолчанию имеет серый фон. Он также не будет участвовать в переходах клавишей Tab.
Пример . Заблокированная кнопка
Давайте заблокируем кнопку с помощью атрибута disabled . Для сравнения рядом пример незаблокированной кнопки (попробуем на нее нажать):
Пример . Заблокированный чекбокс
А теперь давайте посмотрим на заблокированный флажок чекбокса. Для сравнения рядом смотрим пример не заблокированного флажка:
Пример . Заблокированный и отмеченный чекбокс
Давайте посмотрим, как выглядит заблокированный и отмеченный с помощью атрибута checked флажок чекбокс. Для сравнения рядом обратимся к примеру не заблокированного отмеченного флажка:
Пример . Заблокированный текстовый инпут
А теперь давайте заблокируем инпут. Для сравнения рядом посмотрим пример не заблокированного инпута:
Пример . Заблокированный текстареа
А здесь мы увидим заблокированный текстареа (обратите внимание на то, что размер заблокированного textarea можно менять). Для сравнения рядом обратимся к примеру не заблокированного текстареа:
Пример . Заблокированный выпадающий список
Давайте посмотрим как работает заблокированный select . Для сравнения рядом посмотрим пример не заблокированного выпадающего списка: