Тег BUTTON, атрибут disabled

:disabled , :enabled

Эта кнопка серая. Она не доступна для клика. Как написать селектор на основе состояния элемента?

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Псевдоклассы :disabled и :enabled помогают стилизовать интерактивные элементы — на которые можно и нельзя нажать.

Легко применяются к любым элементам, которым можно задать атрибут disabled : , , , , , , , и .

Пример

Скопировать ссылку «Пример» Скопировано

Часто требуется, чтобы на кнопку отправки формы нельзя было нажать, пока не заполнены все поля этой формы. Проще всего заблокировать кнопку атрибутом disabled . Но недостаточно просто указать его в HTML, нужно ещё и при помощи оформления показать пользователю, что кнопка не активна. Как раз для этого нам пригодится псевдокласс :disabled .

Кнопка будет полупрозрачной:

 button:disabled  opacity: 0.5;> button:disabled  opacity: 0.5; >      

Псевдокласс :enabled , наоборот, поможет стилизовать все доступные для взаимодействия элементы. По факту его чаще всего не указывают, потому что записи с ним и без него, как правило, равноценны: .input = .input : enabled .

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Любому селектору, указывающему на интерактивный элемент, дописываем двоеточие и указываем одно из ключевых слов: enabled или disabled .

Как понять

Скопировать ссылку «Как понять» Скопировано

Браузер ориентируется на атрибут disabled и, в зависимости от его наличия или отсутствия, добавляет элементу состояние enabled — доступен, или disabled — недоступен.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Даже если дизайнер забыл про неактивное состояние, обязательно прописывайте его в стилях, чуть приглушая фоновый цвет или делая элемент полупрозрачным — чтобы пользователь точно знал, что с этим элементом взаимодействовать нельзя.

💡 enabled чаще всего не используется, потому что все интерактивные элементы по умолчанию доступны (включены). Это значит, что прописав стили для селектора .input , вы закрываете сценарий с активным элементом.

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 «Выключать» взаимодействие с кнопками или другими элементами формы удобнее именно атрибутом disabled , потому что он сразу же отключает возможность нажать на этот элемент без дополнительных стилей. И, ориентируясь на него, гораздо удобнее прописывать стили для неактивных элементов, используя псевдокласс disabled .

Код для кнопки из моего последнего проекта:

Стили для активной кнопки в обычном состоянии:

 .additional-btn  padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none;> .additional-btn  padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none; >      

Стили для кнопки при наведении курсора или клике:

 .additional-btn:active,.additional-btn:hover  color: #FF5050; transition: none;> .additional-btn:active, .additional-btn:hover  color: #FF5050; transition: none; >      

Стили для кнопки, когда она неактивна:

 .additional-btn:disabled  cursor: default; color: #A44234;> .additional-btn:disabled  cursor: default; color: #A44234; >      

Источник

Не активная кнопка с помощью disabled

Неактивная кнопка disabled

HTML-CSS-JQUERY

В этой статье мы рассмотрим как сделать кнопку не активной, при не выполнении определенных условий в форме отправки данных на сайте. Напишем код для кнопки подтверждающей «Согласие на обработку персональных данных», данная тема сейчас востребована в связи с введение закона о «Персональных данных». То есть пока клиент при отправке формы не установит чекбокс напротив надписи «Согласие на обработку персональных данных», кнопка отправки будет не активна.

Кнопка отправить не активна при CSS disabled

 

Зададим тегу значение disabled, которое задает не активность кнопки «Отправить». И немного украсим нашу кнопку и type «checkbox» с помощью CSS.

body < background-color: #1684af; color: #fff; >label < margin-bottom: 8px; font-size: 13px; >input[type=»checkbox»]:checked, input[type=»checkbox»]:not(:checked) < position: absolute; left: -9999px; >input[type=»checkbox»]:checked + label, input[type=»checkbox»]:not(:checked) + label < display: inline-block; position: relative; padding-left: 20px; line-height: 1; cursor: pointer; >input[type=»checkbox»]:checked + label:before, input[type=»checkbox»]:not(:checked) + label:before < content: ""; position: absolute; left: 0px; top: 0px; width: 12px; height: 12px; background-color: #ffffff; >input[type=»checkbox»]:checked + label:after, input[type=»checkbox»]:not(:checked) + label:after < content: ""; position: absolute; -webkit-transition: all 0.2s ease; -moz-transition: all 0.2s ease; -o-transition: all 0.2s ease; transition: all 0.2s ease; >input[type=»checkbox»]:checked + label:after, input[type=»checkbox»]:not(:checked) + label:after < left: 1px; top: 1px; width: 2px; height: 2px; border: 4px solid #F2622E; >input[type=»checkbox»]:not(:checked) + label:after < opacity: 0; >input[type=»checkbox»]:checked + label:after < opacity: 1; >.check-policy < font-size: 13px; >.btn < padding: 0.75em 1.75em; display: inline-block; line-height: 1; margin: 2em 0; color: #fff; background-color: #F2622E; border: none; >.btn:hover < cursor: pointer; >.btn:disabled, .btn:hover:disabled

А теперь добавим к input JS событие:

 

что бы при нажатии на строчку с «Согласие на обработку персональных данных» кнопка «Отправить» стала активной.

Активная кнопка в HTML с помощью CSS

Посмотреть как это работает можно здесь:

Источник

Атрибут disabled

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

Синтаксис

Значения

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

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

       

Результат данного примера продемонстрирован на рис. 1.

Вид активной и неактивной кнопки

Рис. 1. Вид активной и неактивной кнопки

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

Enable and Disable a Button in JavaScript

While creating user interfaces, you may probably want to make them more dynamic and enable or disable a button programmatically.

Before starting, you need to know that all HTML buttons have a property disabled . Thanks to it, you can enable or disable a button.

 

This article will manipulate the disabled property using a short JavaScript code.

Let me show you how to do that!

1. Create a button in your HTML

The first step is to create a button in your HTML with an id property. It will allow you to select it later in the tutorial.

2. Select your button using JavaScript

The first step in your code is to select the button you want to update. You can do it using the querySelector function, but we will use the getElementById native function because of its simplicity.

It will allow you to target an HTML element based on its id property.

// Select the button element in your HTML code const button = document.getElementById('mainButton')

3. Disable button in JavaScript

As mentioned previously in this article, all HTML buttons have a disabled property that you can use to disable or enable a button.

By default, a button’s disabled property is set to false . It means that by default, a button is active.

If you want to disable a button using JavaScript, you can switch this value to true once you have created and selected the button (steps 1 and 2).

// Disable a button in JavaScript button.disabled = true // 

4. Enable button in JavaScript

Now you know how to disable a button, you can enable it by reverting the true value to false .

// Enable a button in JavaScript button.disabled = false // 

Bonus: How to Disable a Button in JavaScript Based on Condition

Let’s go further and create some code that disables the button only if its text matches a condition.

Here is what you will need to know:

  • create a button in HTML
  • disable a button in JavaScript
  • write a condition using JavaScript
  • get a button text in JavaScript (you will use the innerText property, but don’t worry you will see how to use it below!)

To do so, you can come back to step 1, 2, and 3, except that we disable the button only if the button text is “Can you click me?”.

// Select the button element in your HTML code const button = document.getElementById('mainButton') // Disable the selected button in JavaScript based on a condition // If the button text is 'Can you click me?' if (button.innerText === 'Can you click me?')

If you execute this code in your browser, the button should be disabled. Now, let’s change the condition to another text. For example: button.innerText === "Click here!" , refresh your browser, and the button should be enabled.

Full code to enable and disable a button in JS 👇

     

Thanks for reading. Let’s connect!

➡️ I help you grow into Web Development, and I share my journey as a Nomad Software Engineer. Join me on Twitter for more. 🚀🎒

Источник

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 :-

HTML :-

 

Result :-

disable button

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 :-

CSS :-

button:disabled, button[disabled] < border: 1px solid #999999; background-color: darkgrey; color: #fff; padding: 10px; cursor: not-allowed; >.btn

HTML :-

 

Result :-

style disabled button with CSS

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.

Below code displays the style that can disable hover effect of button :-

CSS :-

.btn < border: 1px solid #999999; background-color: blue; color: #fff; padding: 10px; >.btn:hover:enabled < background-color: black; color: #fff; >button:disabled, button[disabled]

HTML :-

 

Источник

Читайте также:  Python method with return value
Оцените статью