- Отключить/включить ввод с помощью jQuery?
- ОТВЕТЫ
- Ответ 1
- jQuery 1.6 +
- jQuery 1.5 и ниже
- В любой версии jQuery
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- 2018, без JQuery (ES6)
- Ответ 13
- Ответ 14
- Для отключения
- Для включения
- Ответ 15
- Enable/Disable Input fields Using JavaScript
- How to Enable/Disable Input Fields Using JavaScript?
- Approach 1: Enable/Disable Input Fields Using JavaScript Using onclick Event
- Example
- Approach 2: Enable/Disable Input Fields Using JavaScript Using addEventListener() Method
- Example
- Conclusion
- About the author
- Umar Hassan
- Input Text disabled Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- HTMLInputElement: disabled property
- Value
- Examples
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
Отключить/включить ввод с помощью jQuery?
Какой стандартный способ? И, наоборот, как вы включаете отключенный ввод?
ОТВЕТЫ
Ответ 1
jQuery 1.6 +
Чтобы изменить свойство disabled , вы должны использовать функцию .prop() .
$("input").prop('disabled', true); $("input").prop('disabled', false);
jQuery 1.5 и ниже
Функция .prop() не существует, но .attr() делает аналогичное:
Установите отключенный атрибут.
$("input").attr('disabled','disabled');
Чтобы снова включить правильный метод, используйте .removeAttr()
В любой версии jQuery
Вы всегда можете полагаться на фактический объект DOM и, вероятно, немного быстрее, чем два других варианта, если вы имеете дело только с одним элементом:
// assuming an event handler thus 'this' this.disabled = true;
Преимущество использования методов .prop() или .attr() заключается в том, что вы можете установить свойство для набора выбранных элементов.
Примечание: В 1.6 есть метод .removeProp() , который звучит так же, как removeAttr() , но он НЕ ДОЛЖЕН ИСПОЛЬЗОВАТЬ для собственных свойств, таких как ‘disabled’ Выдержка из документации:
Примечание. Не используйте этот метод для удаления собственных свойств, таких как отмеченные, отключенные или выбранные. Это полностью удалит свойство и, после удаления, не может быть добавлено снова элементу. Используйте .prop(), чтобы вместо этих свойств было false.
На самом деле, я сомневаюсь, что для этого метода существует много законных применений, логические реквизиты выполняются таким образом, что вы должны установить их в false вместо «удалить» их, как их «атрибутные» аналоги в 1.5
Ответ 2
Только ради новых соглашений && делая его адаптируемым в будущем (если ситуация не изменится с ECMA6 (. ):
$(document).on('event_name', '#your_id', function() < $(this).removeAttr('disabled'); >);
$(document).off('event_name', '#your_id', function() < $(this).attr('disabled','disabled'); >);
Ответ 3
// Disable #x $( "#x" ).prop( "disabled", true ); // Enable #x $( "#x" ).prop( "disabled", false );
Иногда вам нужно отключить/включить элемент формы, например input или textarea. JQuery помогает вам легко сделать это с установкой отключенного атрибута на «отключено». Например, например:
//To disable $('.someElement').attr('disabled', 'disabled');
Чтобы включить отключенный элемент, вам нужно удалить атрибут «disabled» из этого элемента или удалить его. Например, например:
//To enable $('.someElement').removeAttr('disabled'); // OR you can set attr to "" $('.someElement').attr('disabled', '');
Ответ 4
Ответ 5
Вы можете поместить это где-то глобальное в свой код:
$.prototype.enable = function () < $.each(this, function (index, el) < $(el).removeAttr('disabled'); >); > $.prototype.disable = function () < $.each(this, function (index, el) < $(el).attr('disabled', 'disabled'); >); >
И тогда вы можете писать такие вещи, как:
$(".myInputs").enable(); $("#otherInput").disable();
Ответ 6
Если вы просто хотите инвертировать текущее состояние (например, поведение кнопки переключения):
$("input").prop('disabled', ! $("input").prop('disabled') );
Ответ 7
Теперь нет необходимости в jQuery, и это было некоторое время, поскольку document.querySelector или document.querySelectorAll (для нескольких элементов) выполняют почти то же самое задание, что и $, плюс более явные getElementById , getElementsByClassName , getElementsByTagName
Отключение одного поля класса «вход-флажок»
document.querySelector('.input-checkbox').disabled = true;
document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
Ответ 8
Вы можете использовать метод jQuery prop() для отключения или активации элемента формы или управления динамически с помощью jQuery. Для метода prop() требуется jQuery 1.6 и выше.
Ответ 9
Есть несколько способов их использования: вы можете включить/отключить любой элемент :
$("#txtName").attr("disabled", "disabled");
Если вы используете версию jQuery 1.7 или более поздней версии, используйте prop() вместо attr().
$("#txtName").prop("disabled", "disabled");
Если вы хотите включить любой элемент, вам просто нужно сделать что-то противоположное тому, что вы сделали, чтобы отключить его. Однако jQuery предоставляет другой способ удаления любого атрибута.
$("#txtName").attr("disabled", false);
$("#txtName").removeAttr("disabled");
Опять же, если вы используете версию jQuery 1.7 или более поздней версии, используйте prop() вместо attr(). То есть. Так вы включаете или отключите любой элемент, используя jQuery.
Ответ 10
$('input').attr('readonly', true); // Disable it. $('input').addClass('text-muted'); // Gray it out with bootstrap.
$('input').attr('readonly', false); // Enable it. $('input').removeClass('text-muted'); // Back to normal color with bootstrap.
Ответ 11
Я использовал ответ @gnarf и добавил его как функцию
$.fn.disabled = function (isDisabled) < if (isDisabled) < this.attr('disabled', 'disabled'); >else < this.removeAttr('disabled'); >>;
Ответ 12
2018, без JQuery (ES6)
[. document.querySelectorAll('input')].map(e => e.disabled = true);
Отключить input с id=»my-input»
document.getElementById('my-input').disabled = true;
Вопрос заключается в том с JQuery, это просто FYI.
Ответ 13
Name: function disable() < document.getElementById("myText").disabled = true; >function enable()
Ответ 14
Для отключения
$('#someselectElement').selectmenu().selectmenu('disable').selectmenu('refresh', true); $('#someTextElement').textinput().textinput('disable');
Для включения
$('#someselectElement').selectmenu().selectmenu('enable').selectmenu('refresh', true); $('#someTextElement').textinput('enable');
Ответ 15
Отключить true для типа ввода:
В случае конкретного типа ввода (пример ввода текста)
$("input[type=text]").attr('disabled', true);
Enable/Disable Input fields Using JavaScript
While creating a form or a questionnaire, there is a requirement to prompt the user at a certain point while filling in an input field. For instance, limiting the number of characters within a field i.e. “Contact No”. In addition to that, for applying a prerequisite condition to fill a particular field, etc. In such case scenarios, enabling/disabling input fields in JavaScript is a very convenient approach for both the developer and user’s end.
This tutorial will explain the approaches to enable/disable input fields using JavaScript.
How to Enable/Disable Input Fields Using JavaScript?
To enable/disable input fields using JavaScript, the following approaches can be utilized in combination with the “disabled” property:
Approach 1: Enable/Disable Input Fields Using JavaScript Using onclick Event
An “onclick” event is used to redirect to the specified function. This event can be applied to invoke the corresponding function for enabling and disabling input fields upon the button click.
Example
Let’s have a look at the below-stated example:
< h2 >Enable / Disable Text Field
In the above-stated code, perform the following steps:
- Include an input “text” field having the specified “id” and “placeholder” values.
- Also, create two separate buttons with attached “onclick” events redirecting to two different functions for enabling and disabling the input fields respectively.
Let’s continue to the JavaScript part of the code:
let get = document. getElementById ( «input» )
let get = document. getElementById ( «input» )
In the above code snippet, perform the following steps:
- Declare a function named “disableField()”.
- In its definition, access the created input field by its “id” using the “document.getElementById()” method
- In the next step, apply the “disabled” property and assign it the boolean value “true”. This will result in disabling the input field upon the button click.
- Similarly, define a function named “enableField()”.
- In its definition, similarly, repeat the step discussed for accessing the input field.
- Here, assign the “disabled” property as “false”. This will result in enabling the disabled input field.
In the above output, it can be observed that the input field is disabled and enabled properly upon the corresponding button click.
Approach 2: Enable/Disable Input Fields Using JavaScript Using addEventListener() Method
The “addEventListener()” method is used to attach an event to the element. This method can be implemented to disable and enable an input field based on the attached event and the specified “key”.
- “event” refers to the name of the event.
- “function” points to the function to execute.
- “use” is the optional parameter.
Example
Let’s observe the below-stated example:
< h2 >Enable / Disable Text Field
In the above lines of code:
- Include the stated heading.
- In the next step, repeat the method discussed in the previous approach for including an input field having the specified “id” and “placeholder” values.
Let’s move on to the JavaScript part of the code:
let get = document. getElementById ( «input» )
get. addEventListener ( «keydown» , ( e ) => {
In the above code snippet, perform the following steps:
- Access the input field by its “id” using the “document.getElementById()” method.
- In the next step, apply the “addEventListener()” method and attach an event named “keydown”.
- In the further code, assign the “disabled” property as “false” for enabling the input field.
- Lastly, in the “else” condition, allocate the “disabled” property as “true” for disabling the enabled input field upon pressing the “Enter” key.
From the above output, it is evident that the input field becomes disabled upon pressing the “Enter” key.
Conclusion
The “disabled” property in combination with the “onclick” event or the “addEventListener()” method can be applied to enable/disable input fields using JavaScript. The former approach can be utilized to redirect to the corresponding function to enable/disable the input field upon the button click. The latter approach can be implemented to perform the required functionality based on the attached event and the specified “key”. This article explains how to enable/disable input fields in JavaScript.
About the author
Umar Hassan
I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.
Input Text disabled Property
The disabled property sets or returns whether a text field is disabled, or not. A disabled element is unusable and un-clickable. Disabled elements are usually rendered in gray by default in browsers.
Browser Support
Syntax
Property Values
Technical Details
More Examples
Example
Find out if a text field is disabled or not:
Example
Disable and undisable a text field:
function disableTxt() <
document.getElementById(«myText»).disabled = true;
>
function undisableTxt() document.getElementById(«myText»).disabled = false;
>
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
HTMLInputElement: disabled property
The HTMLInputElement.disabled property is a boolean value that reflects the disabled HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks. A disabled element is unusable and un-clickable.
Value
Examples
HTML
p> label> input id="check-box" name="b" value="1" type="checkbox" disabled /> Check this box! label> p> p> label> input id="toggle-box" name="b" value="2" type="checkbox" /> Enable the other checkbox. label> p>
JavaScript
const checkBox = document.getElementById("check-box"); const toggleBox = document.getElementById("toggle-box"); toggleBox.addEventListener( "change", (event) => checkBox.disabled = !event.target.checked; >, false, );
Result
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.