ediblecode
ediblecode

Reputation: 11971

Issue with jQuery recognising checkbox values?

I am having a problem with my jQuery code in that for some reason it doesn't distinguish between checked and unchecked checkboxes in my situation. It recognises them on the first account (i.e. if it is unchecked to begin with, it recognises that it is in fact unchecked). But if you then uncheck it, it still thinks that it is unchecked.

You can see here: http://jsfiddle.net/3BZp4/1/

When checked, it will copy the row to the second table, but when you uncheck that same row, it still copies to the second table despite the selector asking for only unchecked rows.

$('#one tbody tr td input.checkbox:not(:checked)').on('change', function (e)
{ });

Upvotes: 0

Views: 67

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

You can try something like this:

$(':checkbox').on('change', function() {
  if(this.checked) {
     // do if checked
  } else {
    // do if not checked
  }
});

Your complete code will:

$('#one tbody tr td input.checkbox').on('change', function(e) {
    if (this.checked) {
        var row = $(this).closest('tr').html();
        $('#two tbody').append('<tr>' + row + '</tr>');
    }
});

Check this DEMO

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

Working demo Is this what you are looking for http://jsfiddle.net/gvDGS/2/

API http://api.jquery.com/not-selector/

Please let me know if I missed anything, hope this helps!

code // BInds to all the unchecked but checks if checkbox is checked or not.

$('input[type=checkbox]:not(:checked)').on('change', function() {

   if( $(this).is(':checked') ){
        var row = $(this).closest('tr').html();
        $('#two tbody').append('<tr>' + row + '</tr>');
    }
});

Upvotes: 1

Rob Forrest
Rob Forrest

Reputation: 7450

It looks like that you have bound a function to all input boxes that are currently unchecked. That function will always be bound to those checkboxes regardless of their state thereafter. You should check the checked status as part of the bound function, much the same as thecodeparadox has done.

Upvotes: 2

Related Questions