0

I am having an issue with Enabling a button with a checkbox using JavaScript. Whenever I click the checkbox, the Delete button stays disabled.

The code I am using is as follows:

<script type="text/javascript">
$('#cb_delete').click(function(){

    if($(this).attr('checked') == false){
         $('#btn-delete').attr("disabled","disabled");   
    }
    else {
        $('#btn-delete').removeAttr('disabled');
    }
});

</script>

<button type='submit' name='btn-delete' disabled='disabled' id='btn-delete' class='btn btn-default btn-sm'>Delete</button> 
<td><input type='checkbox' name='cb_delete[]' id='cb_delete' value='$mID'></td>
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
James
  • 557
  • 1
  • 8
  • 22
  • 1
    You could replace everything inside the event handler with just `$('#btn-delete').prop('disabled', this.checked)` – adeneo Jul 16 '16 at 18:45
  • 99% if the time if you see `attr` you really need `prop`. The confusion tends to come from early version of jQuery which mixed both behaviors under the same `attr` method. – Jeremy J Starcher Jul 16 '16 at 18:46
  • Also, if your script tag appears before your `#cb_delete` element is in the DOM, it won't attach the event because it won't find the element. – Alexander O'Mara Jul 16 '16 at 18:47
  • Possible duplicate of [Why is this jQuery click function not working?](http://stackoverflow.com/questions/18602331/why-is-this-jquery-click-function-not-working) – Alexander O'Mara Jul 16 '16 at 18:52

2 Answers2

1

Use:

$('#cb_delete').change(function() {
  $('#btn-delete').prop('disabled', !($(this).is(":checked")));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='submit' name='btn-delete' disabled='disabled' id='btn-delete' class='btn btn-default btn-sm'>Delete</button>
<td>
  <input type='checkbox' name='cb_delete[]' id='cb_delete' value='$mID'>
  <br>OTHERS1:
  <input type='checkbox' name='others1[]' id='other1' value='$oID'>
  <br>OTHERS2:
  <input type='checkbox' name='others2[]' id='other2' value='$iID'>
</td>
Iceman
  • 6,035
  • 2
  • 23
  • 34
  • Thank you for your response. This does work for me, however as I have put the in click event inside the checkbox, if there are multiple checkboxs, it toggles everytime I click a different checkbox – James Jul 16 '16 at 18:52
  • @James Since only one checkbox has id `cb_delete`, i dont think it should be an issue – Iceman Jul 16 '16 at 18:54
  • @James just updated. I added dummy checkboxes. Note that they don't enable or disable the button. – Iceman Jul 16 '16 at 18:58
  • 1
    Thank you very much for clarifying, I understand the concept now. This works perfectly for me, thanks again! – James Jul 16 '16 at 19:00
1

The way you are checking to see if the box is checked or not is not a good way of doing it. Try:

if( $( this ).is( ':checked' ) ) {

}else{

}
Daniel C
  • 2,105
  • 12
  • 18