开发者

Updating classnames according to checkbox status

I have a table with multiple rows, each having it's own checkbox. I have the following script to invert all checkboxes:

$("INPUT[type='checkbox']").each(function(){
    if (this.checked == false) {
        this.checked = true;
    } else {
        this.checked = false;
    }
});

Now, I want that each row (it has it's unique ID - like id='row1' id='row2' etc etc) to have their classnames changed: if the checkbox is going to be checked it should change to class1 else to class2.

How would this be done? I'm new to jQuery so I have no idea how I would get the e开发者_Python百科lement ID or something. I don't know how to match the checkbox with the row.

Thanks in advance.


You can use .closest() [docs] to get the row where the checkbox is in:

$("INPUT[type='checkbox']").each(function(){
    var toRemove = this.checked ? 'class1' : 'class2',
        toAdd = this.checked ? 'class2' : 'class1';

    $(this).closest('tr').add(toAdd).remove(toRemove);
    this.checked = !this.checked;
});

(there are other ways to avoid repeating the class names, but they become less readable)

If the classes are initially set correctly, you can also just use .toggleClass() [docs]

$("INPUT[type='checkbox']").each(function(){
    this.checked = !this.checked;
    $(this).closest('tr').toggleClass('class1 class2');
});


http://jsfiddle.net/sPgGp/

Example here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜