Disabling button with javascript

Как активировать или отключить кнопку с помощью чистого JavaScript и jQuery

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

JavaScript – один из самых популярных языков программирования, применяемых в веб-разработке. Он используется на большинстве сайтов, и все современные браузеры поддерживают его по умолчанию. В этом руководстве мы рассмотрим полезные приемы, которые помогут вам освоить разработку на JavaScript.

К примеру, при создании сайта на основе JavaScript очень часто требуется включать или отключать кнопки в зависимости от каких-то событий. Как правило, подобная необходимость возникает при разработке форм и анкет: кнопка отправки данных должна оставаться неактивной, пока пользователь не заполнит все обязательные поля. После того, как необходимая информация будет введена, кнопка должна стать активной, чтобы пользователь мог нажать на нее и отправить данные на сервер.

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

Сейчас на конкретных примерах мы рассмотрим, как можно включать и отключать кнопки с помощью JavaScript.

Включение и отключение кнопки на чистом JavaScript

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

      
Username: Password:

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

После загрузки формы в коде предусмотрено событие onchange , связанное с изменением состояния текстовых полей для ввода имени и пароля пользователя. Как только пользователь введет какие-либо данные в любое из этих полей, событие onchange сработает, и вызовет функцию включения и отключения кнопки toggleButton .

Функция toggleButton проверяет, ввел ли пользователь данные в оба обязательных поля. Если пользователь ввел имя и пароль, функция изменит состояние disabled на false , что в итоге приведет к активации кнопки отправки введенных данных. Если же одно из обязательных полей осталось незаполненным, свойство disabled получает параметр true , и как следствие этого, кнопка остается неактивной.

В приведенном выше примере для создания кнопки используется элемент , но при желании также можно использовать HTML-кнопку , как показано ниже:

Читайте также:  Название страницы - отображается на вкладке браузера и в поиске

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

Активация и отключение кнопок на jQuery

Теперь разберемся, как реализовать включение и деактивацию кнопок при помощи библиотеки jQuery. Для этого обратимся к примеру кода из предыдущего раздела. Далее показано как выглядит код при использовании jQuery:

      
Username: Password:

Прежде всего, данный код загружает библиотеку jQuery, чтобы мы могли воспользоваться ее средствами для реализации нашей функции. Для изменения состояния кнопки в данном случае используется метод jQuery-объекта, attr .

Метод attr используется в jQuery для установления и получения значений определенных атрибутов элемента. Если передать методу один аргумент, он вернет значение атрибута объекта. При использовании двух аргументов метод установит новое значение атрибута. В нашем случае метод используется для задания значения disabled атрибуту кнопки. Весь остальной код остается без изменений.

Если вы работаете с jQuery 1.5+, вместо метода attr следует использовать prop , как показано во фрагменте кода, приведенном ниже:

//. $('#submitButton').prop('disabled', true);

Если же вам потребуется удалить какой-то из атрибутов элемента, можно воспользоваться методом removeAttr . Результат будет таким же, что и при использовании параметра false для свойства disabled :

//. $('#submitButton').removeAttr('disabled');

Заключение

В этом руководстве на двух конкретных примерах мы рассмотрели различные способы активации и отключения кнопки – с помощью чистого JavaScript, и с использованием библиотеки jQuery.

Наталья Кайда автор-переводчик статьи « How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla »

Пожалуйста, оставьте свои отзывы по текущей теме статьи. Мы очень благодарим вас за ваши комментарии, отклики, подписки, дизлайки, лайки!

Источник

Disable a HTML Button in JavaScript [With Examples]

To disable a button using only JavaScript you need to set the disabled property to false . For example: element.disabled = true .

And to enable a button we would do the opposite by setting the disabled JavaScript property to false .

Here a more complete example where we select the button and then we change its disabled property:

// Disabling a button using JavaScript
document.querySelector('#button').disabled = true;
// Enabling a disabled button to enable it again 
document.querySelector('#button').disabled = false;

These are the steps we have to follow:

The disabled property reflects the HTML attribute disabled and provide a way to change this property dynamically with JavaScript.

Disable button example

For demo purposes and to keep it as simple as possible we’ll be disabling the button when clicking on itself:

const button = document.querySelector('#button');

const disableButton = () =>
button.disabled = true;
>;

button.addEventListener('click', disableButton);

Here’s the codepen so you can test it out yourself and play a bit more with it by changing the code:

If you are using jQuery, check out our article on how to disable a button using jQuery. The process is pretty similar.

References

Источник

Disable a Button with JavaScript

Javascript Course - Mastering the Fundamentals

Many times in our program, we may need to disable or enable a button in our webpage based on certain conditions being fulfilled or not, and for that, we must be aware about the ways how to do it.

Introduction

The button element is one of the few elements in HTML that can have its state, i.e., either being enabled to accept a click or it could be disabled.

For example — Suppose we are asking the user to fill out a form on our website, and we only want to enable the submit button when the user has clicked on the ‘They have read the terms and conditions’ option, or they have filled some mandatory input field. So in order to do that, we have a particular property associated with every button element in HTML, the disabled property. We can use the disabled property to toggle the state of a button’s activeness to be either true or false , and through this, we can enable or disable a button.

Let’s understand it better with the help of an example.

Program to Disable a Button Using Javascript Disable Button Property

The disabled property in JavaScript is a property associated with every button element, and in order to make it work, we first need to capture that specific button that we want to target through either the querySelector , the getElementById method, the getElementByClassName method, the getElementByTagName method or any other element selector method that we want to use.

After having the button, we can now use the disabled property to make its state active or inactive. To make it inactive, we can set its value to true.

And to make it active again, we can simply set its value to false.

We will not be hardcoding enabling or disabling buttons like this in actual programs; we want this to happen automatically when a specific condition is being met.

Now let’s see an example to understand it better.

Examples of JavaScript Disable Button

Example 1 — Basic Implementation of the Javascript Disable Button property

Output before clicking the button

output-before-clicking-disable-button

Output after clicking the button

output-after-clicking-disable-button

We can see that after clicking the button, the disableButton() function got executed, and it made the button’s background gray out, denoting it is now not clickable, i.e., the button is disabled now.

Example 2 — Implementing the Javascript Disable Button Property into an Actual form Element

Output before selecting checkbox

output-disable-button-into-actual-form-element-before-selecting

Output after selecting checkbox

output-disable-button-into-actual-form-element-after-selecting

We can see here the submit button is disabled by default, and it gets clickable only after the user has selected the required checkbox.

Conclusion

  • Every button element in HTML has a property named disabled to toggle its state of activeness and inactiveness.
  • For that, we first need to capture that specific button using query selectors, and after that,
  • We can set the button.disabled = true; to disable that button and button.disabled = false; to enable it back again.
  • We can use this implementation to make a button active or inactive based on certain specific conditions being met or not, for example — enabling the submit button only if the user has filled all the mandatory fields, etc.

Источник

How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla

Sajal Soni

Sajal Soni Last updated Jul 19, 2021

In this article, we’ll discuss how you can enable or disable a button with JavaScript. First, we’ll go through how it works in vanilla JavaScript, and later on we’ll see how to do it with jQuery.

JavaScript is one of the core technologies of the web. The majority of websites use it, and all modern web browsers support it without the need for plugins. In this series, we’re discussing different tips and tricks that will help you in your day-to-day JavaScript development.

When you’re working with JavaScript, more often than not you need to enable or disable a button based on some actions. Usually, when you’re working with forms, you want to keep the submit button disabled until a user fills all the mandatory fields in a form. Once a user fills all the mandatory fields, you would like to automatically enable it so that the user can click on a button to submit the form.

In HTML, a button element has its own state, and thus, you can keep it either enabled or disabled. For example, when a form is loaded, you can keep a button in the disabled state. Later on, you can enable it with the help of JavaScript.

Today, we’ll discuss how you can enable or disable a button with JavaScript with a couple of real-world examples.

Enable or Disable a Button With Vanilla JavaScript

In this section, we’ll discuss a real-world example, which demonstrates how you can enable or disable a button with vanilla JavaScript.

Let’s go through the following example.

Источник

Оцените статью