Как активировать элемент, используя jQuery и JavaScript. JQuery - установить значение атрибута


Иногда нужно сделать активными или неактивными текстовое поле, радиокнопки или чекбокс. Как сделать это динамически, не перезагружая страницу? Для этого можно использовать JavaScript и jQuery prop . HTML-элемент активируется путем установки свойства disabled в true .

С помощью jQuery можно выбрать элемент, который нужно включить или выключить, и изменить это свойство, используя функции prop() или attr() , в зависимости от того, какая версия jQuery применяется.

Функция prop() была добавлена в jQuery 1.6 и это стандартный метод для работы со свойствами. А функция attr() делает то же самое в jQuery 1.5 и ниже.

Также можно активировать или отключить любой элемент HTML , используя JavaScript . Все, что нужно, это найти элемент по id и установить его свойство disabled в true или false .

Как сделать активным/неактивным текстовое поле с помощью JavaScript

В этом примере есть HTML-форма , текстовые поля и пара кнопок, чтобы делать текстовое поле активным или неактивным. Здесь я использую простой JavaScript , без jQuery prop checked .

Шаги будут следующими:

  • Используйте функции enable() и disable() с кнопками, чтобы включать или выключать текстовое поле.
  • Используйте getElementById() , чтобы получить доступ к текстовому полю.
  • Установите поле disabled в true или false .
  • Вот пример HTML-файла c решением на основе JavaScript :

    Как включать или выключать ввод с помощью JavaScript

    Включение и выключение ввода с помощью JavaScript
    Введите ваше имя:
    Деактивировать текстовое поле Активировать текстовое поле function disable() { document.getElementById("name").disabled = true; } function enable() { document.getElementById("name").disabled = false; }

    При клике по кнопке «Деактивировать текстовое поле » вызывается функция disable() (не путайте с jQuery prop disabled ), и свойство disabled текстового поля устанавливается в true. Поэтому вы не можете больше вводить текст в это поле, оно не активно. При этом можно заново активировать текстовое поле, кликнув по кнопке «Активировать текстовое поле ». Она вызовет функцию enable() , которая сбросит свойство disabled в false .

    Как включить/выключить текстовое поле с помощью jQuery?

    Ниже приведен код, основанный на jQuery , который делает то же самое. В этом примере мы использовали функцию prop() . Если вы пользуетесь версией jQuery 1.5 или старше, замените prop() на attr() .

    Так же, как и в предыдущем примере, у нас есть две кнопки btn_enable и btn_disable , чтобы включать и выключать текстовое поле. Подключим, обработчик событий, используя функцию click() , которая вызывается при загрузке страницы.

    В обработчике события мы находим текстовое поле с помощью селектора ID в jQuery , например, $(«#name») и затем вызываем prop(«disabled», false») , чтобы отключить это текстовое поле.
    Когда пользователь нажимает кнопку «включить », мы устанавливаем свойство disabled в true , вызывая jQuery prop(«disabled» , true ). Это заново активирует текстовое поле. Помните, что нельзя ввести текст в отключенное поле.

    Как включить или выключить текстовое поле с помощью jQuery Включение и выключение текстового поля, используя jQuery Введите ваше имя:
    Выключить ввод Включить ввод

    $(document).ready(function() {
    $("#btn_enable").click(function(){ $("#name").prop("disabled", false); });
    $("#btn_disable").click(function(){ $("#name").prop("disabled", true); });
    });

    Можете протестировать это, запустив пример у себя в браузере. Только не вызывайте функцию removeProp() , чтобы заново включить кнопку. Она удалит атрибут «disabled » из текстового поля, поэтому нельзя будет снова его отключить в будущем. Вместо этого используйте метод jQuery prop disabled .

    Вот скриншот того, как будет выглядеть страница в браузере вроде Edge или Chrome .

    В этом примере мы отключили текстовое поле и заново включили его. Для этого можно использовать JavaScript или jQuery .

    Перевод статьи “How to enable/disable an element using jQuery and JavaScript? Example ” был подготовлен дружной командой проекта .

    Хорошо Плохо

    У меня есть следующий HTML-код с двумя элементами, имеющими одно и то же имя

    Через JQuery я хочу установить флажок enable. Итак, я использую что-то вроде этого:

    $("#chk0").attr("disabled",false);

    Но это не работает. Я предполагаю, что JQuery путается с двумя элементами с одинаковым именем. К сожалению, я не могу избежать использования двух разных имен, потому что, когда форма размещена, я хочу, чтобы все флажки были размещены (а не только те, которые были отмечены). Следовательно, я должен использовать скрытый элемент с тем же именем. Итак, вернемся к вопросу, как я могу включить флажок через JQuery в приведенном выше сценарии? Есть ли параметр "type" для attr, который отделяется от флажка?

    6 ответов

    Некоторые вещи до фактического кода.

    хеш (#), который вы используете в качестве селектора, предназначен для идентификаторов, а не для имен элементов. также отключенный атрибут не является истинным ложным сценарием.. если он отключил атрибут, это значит, что это правда.. вам нужно удалить атрибут и не установить его в false. Также есть селектора форм, которые идентифицируют конкретные типы элементов в форме.

    поэтому код будет

    $("input:checkbox").removeAttr("disabled");

    Приведение ответа в актуальное состояние

    Вы должны использовать метод .prop() (добавленный после версии v1.6)

    $("input:checkbox").prop("disabled", false); // to enable the checkbox

    $("input:checkbox").prop("disabled", true); // to disable the checkbox

    Серьезно, просто не используйте jQuery для этого. disabled - это логическое свойство элементов формы, которое отлично работает в каждом крупном браузере с 1997 года, и нет никакого способа, чтобы было проще или интуитивно изменить, отключен ли элемент формы.

    И строка JavaScript, чтобы включить этот флажок:

    Document.getElementById("chk0_checkbox").disabled = false;

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

    $("#chk0_checkbox").disabled = false;

    "True" и "False" не работают, отключить, установить значение "отключено".

    $(".someElement").attr("disabled", "disabled");

    Чтобы включить, удалите.

    $(".someElement").removeAttr("disabled");

    Кроме того, не беспокойтесь о выборе нескольких элементов, jQuery будет работать на всех из них, которые соответствуют. Если вам нужен только один, вы можете использовать много вещей: во-первых,: последний, n-й и т.д.

    Вы используете имя, а не id, как другое упоминание - помните, что если вы используете id valid xhtml, необходимо, чтобы идентификаторы были уникальными.

    Animation looks pleasing to the eye, but creating animation is not an easy job. It’s important to take into account the effect that animations can have on performance, as even the coolest animations can have negative effects and downgrade user experience. Luckily, jQuery has some inbuilt methods to implement simple animations with ease. These methods are named in such a way that they are clearly labeled for their use and functionality. In this short post, we’ll look at each of these methods in action. These animation methods have one thing in common - accepted parameters. The following 3 parameters are applicable for all methods:
    • Duration: Optional parameter. Either string or number specifications can be used to determine the amount of time given for the animation to complete. The default value is 400 milliseconds. It also accepts “slow” or “fast” string values where “fast” indicates duration of 200 milliseconds and “slow” indicates 600 milliseconds.
    • Easing: Optional. Easing indicates the speed of the animation at different points during the animation. jQuery provides inbuilt swing and linear easing functions to help you play with this parameter.
    • Callback: Optional. A function that may be executed after the animation is complete.
    fadeIn() The fadeIn() method gradually changes the opacity of the selected element from hidden to visible. It changes the opacity value from 0 to 1. It will not work on hidden items. To use this method,

    $("#elm").fadeIn("fast");
    $("#elm").fadeIn(1000); // 1 second

    fadeOut() As you may have guessed, this is the opposite of fadeIn(). This method gradually changes the opacity of the selected element from visible to hidden. It changes the opacity value from 1 to 0. Once the opacity reaches 0, the jQuery set display property is set to none. To use this method:

    $("#elm").fadeOut("slow");
    $("#elm").fadeIn(2000); // 2 seconds

    fadeTo() The fadeTo() method is similar to the fadeIn() method but it gives the option to control the opacity of the element. You can specify the opacity value, as shown here:

    $("#elm").fadeTo("slow", 0.3); //The opacity value is 0.3

    The above code will change the opacity of the element gradually to 0.3.

    fadeToggle() This method is a combination of fadeIn() and fadeout(). If the elements are faded out, fadeToggle() will fade them in and when the elements are faded in, fadeToggle() will fade them out. Like this:

    $("#elm").fadeToogle("slow");
    $("#elm").fadeToggle("slow", function(){
    console.log("The fadeToggle is finished!");
    });

    slideUp() The slideUp() method slides-up the selected element to hide it. This method internally controls the height of the element. Once the height reaches 0, it sets the display property to none in order to hide it. To implement it, use the following code:

    $("#elm").slideUp(); //Uses default value of 400 milliseconds for duration.
    $("#elm").slideUp(500);

    slideDown() This method works opposite to the slideUp() function. It slides-down the selected element to show it. This method changes the height of the matched elements from 0 to the specified maximum height. Thus, it gives the element a slide down effect. To implement it, use the following code:

    $("#elm").slideDown(); //Uses default value of 400 milliseconds for duration.
    $("#elm").slideDown(1000);

    slideToggle() This method is a combination of slideUp() and slideDown(). Internally this method also makes use of the display style property. While sliding up, when the height of the element reaches 0 it sets the display style property to "none". While slide down it sets the "inline" value of the display property. Based on the value of the display property, it determines whether to slide up or down. To implement it:

    $("#elm").slideToggle("slow", function() {
    console.log("Animation complete.");
    });

    Bonus tip: If you want to disable all the animation, set jQuery.fx.off property to ‘true’. This is quite useful when your jQuery code uses animation heavily and you need to disable it. Instead of visiting every single line and modifying it, it’s better to use this property to disable animation completely.

    Conclusion This post talks briefly about various inbuilt animation methods available in jQuery. These methods can perform animations like fading and sliding in both directions. These methods also accept duration to control the speed of your animation. They are simple to use and allow you to implement simple animation with hardly any effort. Have fun playing with them!

    Steps is a simple, lightweight and easy to configure jQuery plugin which allows you to create a step wizard from any grouped elements. This plugin is simple to use and it is only dependent on jQuery library. It comes with various options for customizing the wizard. You can:

    • Set the starting number which starts the wizard at a specific step number
    • Implement ‘showBackButton,’ which indicates whether the back button will be visible or not – quite useful if you want to restrict your users from going back to the previous step
    • Implement ‘show/hide’ footer buttons – when footer buttons are not visible, then the user can move back and forth on clicking the step number buttons
    2. formToWizard

    FormToWizard is a jQuery plugin which allows you to turn any web form into a multi-step wizard with the help of jQuery library. In order to determine the number of steps involved, this plugin first selects all fieldsets and optains the size of this wrapped set. Next, it iterates through this wrapped set (that returned all fieldsets), wraps each fieldset into a div and appends a paragraph that will hold the “back” and “next” buttons. You can also customize the name of the previous and next buttons.

    3. SmartWizard http://techlaboratory.net/smartwizard

    SmartWizard is a flexible and heavily customizable jQuery step wizard plugin with Bootstrap support. It is easy to implement and gives a neat and stylish interface for your forms, checkout screen, registration steps etc. There are a lot of features on top of the built-in Bootstrap support, including:

    • Responsive themes
    • Customizable toolbars
    • URL navigation and step selection
    • Customizable options,
    • Public methods,
    • Event support,
    • Keyboard navigation,
    • Multiple wizard instances on the same page
    A neat thing about SmartWizard is that the author of this plugin regularly updates the plugin based on the user’s feedback. Based on the user’s feedback, the recent version 4.0 has been completely rewritten from scratch, making it more powerful, robust, scalable, and customizable.4. Material Bootstrap Wizard https://github.com/creativetimofficial/material-bootstrap-wizard

    The Material Bootstrap Wizard is a jQuery plugin which is a fully responsive wizard, inspired by the famous Google"s Material Design. It is one of the handiest elements that can be used inside a project. Material Bootstrap Wizard breaks the long html form into chunks and lets the user see it one step at a time. This way, the user only has to focus on the current step without being overwhelmed. They will, however, be able to see how many steps they have remaining, so they can assess approximately how long the process will be.

    5. Wizard.js https://github.com/jeffreypolk/bootstrap-wizard

    Wizard.js is a jQuery step wizard plugin which uses the bootstrap"s modal component to display any type of content in a step-by-step wizard. It takes care of the plumbing for moving back and forth between steps, validation, hooks for key events, etc. The wizard depends on structured HTML to define the wizard and the steps for it. The order of the steps presented is defined by the order of the divs within the wizard. There are lots of customization options available to play around. Each step of a wizard can be validated before moving onto the next step using form validation or custom validation.

    6. Stepform https://github.com/masade/stepform
    StepForm is a simple and lightweight jQuery plugin that converts any form into a sliding form of step by step wizard. It is an ideal choice for creating sign-up forms. It also performs the validation using a data-validate attribute and so the user can slide to the next step only after any errors on inputs on the current slide have been validated. It also supports keyboard interactions using enter and tab keys to move to the next step or to the next field.7. jQuery Steps https://github.com/rstaib/jquery-steps

    JQuery Steps is a smart UI component which allows you to easily create wizard-like interfaces. This plugin groups content into sections for a more structured and orderly page view. Furthermore, it is as simple as 1-2-3 to add plugins such as jQuery Validation which can prevent step changing or submission. It supports:

  • HTML5 support
  • Accessibility support
  • State persistence
  • Form validation using any validation plugin of your choice
  • Cool transition effects
  • Easy Navigation
  • Keyboard navigation
  • Multiple wizards on the same page
  • It is very lightweight (only 2.9KB minified) and works with all modern browsers.

    Возвращает или изменяет значение свойств выбранных элементов страницы (разница и связь между атрибутами и свойствами). Функция имеет четыре варианта использования:

    возвращает значение атрибута propName у выбранного элемента. Если выбрано несколько элементов, то значение будет взято у первого. Метод возвращает значение undefined в случае, если на первый из выбранных элементов не установлено указанное свойство или набор выбранных элементов пуст.

    во всех выбранных элементах, свойство propName примет значение value .

    во всех выбранных элементах изменит значения группы свойств propName1, propName2, ... сделав их равными value1, value2, ... соответственно.

    свойству propName будет присвоено значение, возвращенное пользовательской функцией (если она ничего не вернет, то свойство просто не изменит своего значения). Функция вызывается отдельно, для каждого из выбранных элементов. При вызове ей передаются следующие параметры: index — позиция элемента в наборе , value — текущее значение свойства propName у элемента.

    Примеры использования:

    Замечание 1 : важно отметить, что используя метод.prop(name) , вы получите значения свойства только для первого элемента из всех выбранных. Если вам нужны значения всех элементов, то следует использовать конструкции типа .map() или .each() .

    Замечание 2 : в IE до 9 версии, использование prop для установки значений отличных от простых типов (число, строка, boolean) приводит к утечке памяти, если это свойство не будет удалено (с помощью .removeProp()) до удаления этого элемента из DOM. Поэтому, для установки собственных данных объектам DOM, лучше использовать .data() .

    Замечание 3 : не используйте .removeProp() как аналог присвоения свойству значения false . Удалив нативное (родное, созданное программой, а не пользователем) свойство у DOM-объекта вы не сможете его потом вернуть.

    Prop() удобен для работы с атрибутами, не требующими указания значений (checked и disabled в input-элементах), в большинстве других случаев, для работы с атрибутами лучше использовать .attr() .

    В действии

    Сделаем все флажки неактивными:

    ~lt~!DOCTYPE html~gt~ ~lt~html~gt~ ~lt~head~gt~ ~lt~style~gt~ img{padding:10px;} div{color:red; font-size:24px;} ~lt~/style~gt~ ~lt~script src="http://code.jquery.com/jquery-latest.js"~gt~~lt~/script~gt~ ~lt~/head~gt~ ~lt~body~gt~ ~lt~input type="checkbox" checked /~gt~ ~lt~input type="checkbox" /~gt~ ~lt~input type="checkbox" /~gt~ ~lt~input type="checkbox" checked /~gt~ ~lt~script~gt~ $("input").prop({ disabled: true }); ~lt~/script~gt~ ~lt~/body~gt~ ~lt~/html~gt~

    Ссылки
    • Список всех функций для манипуляции с элементами страницы

    Поисковые ключи:

    • свойства элементов на странице
    • значение свойства
    • получить значение свойства
    • изменить значение свойства
    • установить значение свойства
    • присвоить значение свойству
    • .prop()
    • prop()




    

    2024 © gtavrl.ru.