2

I would like to catch a checkbox change and also catch the index of the checkbox selected or unselected. I'm wondering if this could be ok.

$("input[type='checkbox']").change(function () {
  $("input[type='checkbox']").each(function (i) {
    //my code here
    switch (i) {
      case 0:
        break;
      case 1:
        break;
          .
          .
    }
  });
});

My html is something like this:

<table>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
<td id='led' bgcolor=#cccccc>OFF</td>
<td><input type='checkbox' name='' value='' ></td>
</tr>
<tr>
</table>

So I would like to detect what box was selected and then change the led to ON and to red background color. On the other hand if the the box is unselected I want to return the LED to OFF and change color to #cccccc

Ben McCormick
  • 23,365
  • 11
  • 48
  • 70
electronixG
  • 120
  • 1
  • 11
  • 2
    There are several syntax errors in your code, `)};` should be `});`. – undefined Apr 06 '13 at 14:08
  • you can access you checked/unchecked checkbox using `$(this)` inside your `$("input[type='checkbox']").change(function() {});` – Ejaz Apr 06 '13 at 14:11
  • What's your HTML? And, to second [charlieftl](http://stackoverflow.com/questions/15851894/catching-chekbox-change-and-index#comment22559002_15851894), without knowing your objective we can't provide a coherent/sensible answer or suggestions. – David says reinstate Monica Apr 06 '13 at 14:13
  • what is objective? there are much easier approaches. Provide more details on use case and what you want to know about the checkboxes. A demo in jsfiddle.net always helps get better responses – charlietfl Apr 06 '13 at 14:13

3 Answers3

5

Without further details, this is the most generic code I can offer (with more information comes great, uh, answers):

$('input:checkbox').change(function(){
    // caching the $(this) jQuery object, since we're using it more than once:
    var that = $(this),
         // index of element with regard to its sibling elements:
        index = that.index(),
        // index with regard to other checkbox elements:
        checkboxIndex = that.index('input:checkbox');

        if (this.checked){ // this.checked evaluates to a Boolean (true/false)
            // this block executed only if the checkbox *is* checked
        } else {
            // this block executed only if the checkbox is *not* checked
        }
});

Edited to address requirements in (edited/clarified) question:

$('input:checkbox').change(function () {
    var that = this,
        $that = $(that),
        led = $that.closest('tr').find('td:first-child');
    led.removeClass('on off').addClass(function(){
        return that.checked ? 'on' : 'off';
    });
});

JS Fiddle demo.

Coupling the above jQuery with the following CSS:

.led,
.led.off {
    background-color: #ccc;
}

.led.on {
    color: #000;
    background-color: #f00;
}

And HTML:

<table>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
    <tr>
        <td class='led'>OFF</td>
        <td>
            <input type='checkbox' name='' value='' />
        </td>
    </tr>
</table>

Note that I've replaced the id="led" wtih class="led", since an id must be unique within the document. This is important, when it comes to JavaScript, and HTML validity.

References:

David says reinstate Monica
  • 230,743
  • 47
  • 350
  • 385
  • +1; However, to make sure you're aware, the biggest issue is that you're creating one local variable (`that`) and two global variables (`index` and `checkboxIndex`). Also, if you do go with the option of wrapping `this` into a jQuery object, you might as well use it in place of `this.checked` (eg `that.prop('checked')`, to make sure `this` wasn't modified someplace else. – vol7ron Apr 06 '13 at 14:24
  • 2
    Where am I creating global variables? All the variables follow the `var` declaration, in the local scope. Or am I missing/misunderstanding something? And I dislike using `that.is(':checked')` and `that.prop('checked')`, simply because it's needlessly expensive (even though I've not cached the `this` node). – David says reinstate Monica Apr 06 '13 at 14:27
  • Yes they are all local variables – electronixG Apr 06 '13 at 14:36
  • @electronixG: no they are not all local variables -- `var a=1,b=2,c=3;` is not the same as `var a=1;var b=2;var c=3;` see http://stackoverflow.com/a/7384541/183181 – vol7ron Apr 06 '13 at 17:11
  • @DavidThomas: the point is, if you're going to wrap `this` in a jQuery object, then it's easier to maintain that code if you use the jQuery object elsewhere, yes it is more expensive, but you confuse someone who comes behind you by using `that`,`this`,and `$(this)` all over the place and you've already created most of the overhead (expense) when you chose to use jQuery in the first place. – vol7ron Apr 06 '13 at 17:16
0

You can do if a checkbox is checked or not using this inside your each function code:

if ( $(this).is(':checked') ) {
  // ...
} else {
  // ...
}
undefined
  • 136,817
  • 15
  • 158
  • 186
IndoKnight
  • 1,766
  • 1
  • 19
  • 29
  • why even create a new variable? `if(this.checked){...}` – vol7ron Apr 06 '13 at 14:18
  • 2
    Sorry, where is the new variable here? – IndoKnight Apr 06 '13 at 14:23
  • I *think* s/he's referring to the use of the jQuery-wrapped `$(this)`, rather than using `this`; since `this.checked` returns the same Boolean value as `$(this).is(':checked')`. But, honestly, I'm guessing. – David says reinstate Monica Apr 06 '13 at 15:28
  • Right, please excuse my wrong choice of words. `$(this)` is creating a new object, technically there are functions/variables within that object, but that's not what I meant. I was merely getting to the fact that `this.checked` is a lot less expensive than `$(this).prop('checked')` – vol7ron Apr 06 '13 at 17:10
  • Agreed. Thanks for your inputs! – IndoKnight Apr 06 '13 at 19:13
-1
$('input:checkbox').change(function() {
   if (this.checked) {
      // your code here
      alert(this.value);
   }
});
vol7ron
  • 35,981
  • 19
  • 104
  • 164