J. Doe J. Doe - 6 months ago 14
jQuery Question

If checkbox is checked, show "Activated" else show "Deactivated"

I have this checkbox.

<input type="checkbox" value="" name="checkycheck"><label for="checkycheck">Activated</label>

I'm figuring out how to show "Activated" as the label when the input is checked. When the input is not checked, show "Deactivated".

So to explain it more:

if(checkycheck == checked) {
echo 'Activated';
} else {
echo 'Deactivated';

That kind of looks like PHP but I want that in real time in jQuery. I have tried looking on Google but I'm really not much getting out of it and I hope that someone with more jQuery knowledge than me can help me out.

Thanks a lot.


You should give your input an id, because that is what a label can reference with the for attribute. With that change, the code could look like this:

$('#checkycheck').change(function () {
  $('label[for="checkycheck"]').text(this.checked ? 'Activated' : 'Deactivated');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" value="" name="checkycheck" id="checkycheck">
<label for="checkycheck">Activated</label>

Note the change() call near the end which makes sure the code is also executed on page load, setting the text correctly from the start.