d4ne d4ne - 2 months ago 9
jQuery Question

on checked checkbox set attribute otherwise remove attribute

I'm trying to change a

disabled
attribute on a button, in case the checkbox:

<input type="checkbox" id="terms" class="styled" name="terms">Accept <a href="#">terms of service</a>


would be checked, the
disabled
attribute should be deleted, otherwise it should stay on the button element.

I got it working the following way:

if(document.getElementById('terms').checked) {
$("#registerButton").removeAttr('disabled');
}else{
$("#registerButton").attr('disabled','disabled');
}


Sadly this will only work once. Once i check the checkbox the button would not be changed. Is there such a function is onchange edit the button?

Answer

You can do it like following.

$('#terms').change(function() {
    $("#registerButton").prop('disabled', !this.checked);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="terms" class="styled" name="terms">Accept <a href="#">terms of service</a>

<button id="registerButton">Register</button>