How do I add / remove an attribute from input?

There is a task: by clicking on the button to add / remove an attribute from the input. I tried to do this:

$("#button").click(function() {
  $("#input").toggle(
    function() {
      $(this).attr('disabled', true);
    },
    function() {
      $(this).removeAttr('disabled');
    }
  );
})

However, toggle only hides and opens the input, and doesn't add anything anywhere.

I read that toggle is outdated. What is the alternative?

Author: Алексей Уколов, 2016-07-18

3 answers

The .prop() method should be used to set disabled and checked instead of the .attr() method. http://api.jquery.com/prop/

$("#button").click(function() {
    $('#input').prop('disabled', function( i, currentValue ) {
        return !currentValue;
    });
});

Interactive example

Note that the method .prop() operates directly on the DOM element without updating the markup, unlike the .attr () method. Therefore, it works faster and is recommended for use, but in the rest of the code, you will also need to use it, and not. attr (), to operate current values.

 3
Author: Алексей Уколов, 2016-07-18 19:33:17

I didn't really understand the meaning of the code, but I would answer the task like this:

$("#button").on('click', function(e){
  var val = $('#input').attr('disabled');
  $('#input').attr('disabled', !val);
});
 1
Author: Denny, 2016-07-18 19:26:09

You can do the following

$("#button").on('click', function() {
  if($("#input").prop('disabled')) {
    $("#input").prop('disabled', false);
  } else {
    $("#input").prop('disabled', true);
  }
});
 1
Author: cheops, 2016-07-18 19:26:24