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>