Jojo Yo
Jojo Yo

Reputation: 41

Remove disabled attribute from a form field when toggle a button

I am trying to remove the disabled attribute when I toggle a button (to on) and viceversa.

At this time I have only created a click event to remove the disabled attr.

The HTML is : Input:

 <input id="wb_owner_field" type="text" disabled value="" placeholder="" class="form-control">

And the on/off toggle when is off it has the class : switch-off and when its on it has class switch-on

<div id="wb_owner_toggle" class="switch-off switch-animate" style="">
  <input type="checkbox" data-toggle="switch">
  <span class="switch-left"></span><label>&nbsp;</label>
  <span class="switch-right"></span>
</div>

Code used until now.

$("#wb_owner_toggle").click(function(){
      $('#wb_owner_field').prop("disabled", false);
});

Basically I need to fir-up when the toggle div class is changed and to remove or add the disabled attr on the field based on the class.

Upvotes: 1

Views: 1566

Answers (3)

Vlad DX
Vlad DX

Reputation: 4730

The right answer is that disabled attribute is boolean attribute.

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes

Please, read carefully. The false value – is the absence of that attribute.

disabled="false" is totally incorrect.

So, the right way to remove it by jQuery is:

element.removeAttr('disabled');

If this algorithm confirms your case, the code will be:

$("#wb_owner_toggle").click(function() {
  if ($(this).hasClass('switch-off')) {
    $('#wb_owner_field').removeAttr('disabled');
  }
  else {
    $('#wb_owner_field').attr('disabled');
  }
}); 

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30557

Use hasClass()

$("#wb_owner_toggle").click(function(){
      if($(this).hasClass('switch-off')){
            $('#wb_owner_field').prop("disabled", false);
      }
});

Upvotes: 1

Petko Kostov
Petko Kostov

Reputation: 367

Here you go

$("#wb_owner_toggle").click(function(){
      var owner_el = $('#wb_owner_field');
      owner_el.attr('disabled', !owner_el.is(':disabled'));
});

Upvotes: 1

Related Questions