2

I'm trying to disable a button by adding a class if a particular radio button is chosen. Here is my not working first iteration of Javascript.

var slug = $("input[name='slug']:checked").val();

$(document).on('change', 'input', function() {
  if (slug == "the_lone_snitch") {
    $(".button").addClass("disabled")
  }
});

So, Every time the radio button is not "the_lone_snitch it removes the disabled class and every time it's equal to "the_lone_snitch" it adds the class.

Bitwise
  • 8,021
  • 22
  • 70
  • 161
  • http://stackoverflow.com/questions/2330209/jquery-checkbox-enable-disable – Robert May 11 '17 at 02:58
  • per the link @RobertRocha referenced, you may want to consider toggling the disabled attribute instead of a class, since a class along won't actually disable the button, and you can use the attribute as a styling selector instead. – scottohara May 11 '17 at 03:19
  • 1
    Always provide all necessary code for best possible solution – Robert May 11 '17 at 03:35

2 Answers2

3

Note that to disable a button you want to set the disabled property to true, not just add a class. Anyway...

Your code only gets the value of whatever radio button was checked at the time the first line runs, which is before the change event occurs. You need to get the current value inside the change handler, and you need an else case to remove the class when not required:

$(document).on('change', 'input', function() {
  var slug = $("input[name='slug']:checked").val();
  if (slug == "the_lone_snitch") {
    $(".button").addClass("disabled").prop("disabled", true);
  } else {
    $(".button").removeClass("disabled").prop("disabled", false);
  }
});

You can simplify it a bit though, because inside the handler you can just use this.value (where this is the just-clicked element) and using the .toggleClass() method, which accepts a boolean to say whether to add or remove the class.

$(document).on('change', 'input[name="slug"]', function() {
  var disable = this.value == "the_lone_snitch";
  $(".button").toggleClass("disabled", disable)
    .prop("disabled", disable);
});
.disabled { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="radio" name="slug" value="abc">Enabled</label>
<label><input type="radio" name="slug" value="the_lone_snitch">Disabled</label>
<br>
<button class="button">Button</button>
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

First let me know if your above code is adding the disabled class or not. If yes, then what you missed is giving it an else part when slug is not equal to "the_lone_snitch"

Your full code should look like

var slug = $("input[name='slug']:checked").val();

$(document).on('change', 'input', function() {
  if (slug == "the_lone_snitch") {
    $(".button").addClass("disabled")
  }
  else{
    //This will enable to button when radio button is not equal to "the_lone_snitch"
    $(".button").removeClass("disabled")
  }
});
Ankit
  • 34
  • 3