开发者

jQuery: How do I check checkboxes by id and value (checking some, not all, checkboxes in a list)

I need to check a few checkboxes in a list of checkboxes where the IDs are the same but the values are di开发者_开发知识库fferent.

I guess this is a specific selector that needs constructing, but how?


This is a big NONO:

where the IDs are the same

id's have to be unique. Use classes instead for such purposes. After you set a specific classname to all those elements, just select them with the class selector

$('.classname')

If you need more flexibility to sort out which elements you need to check, use jQuerys

.filter()

method.


The IDs should be unique for each checkbox - you can have the same name or class attributes, but IDs should be different.

Do the checkboxes you do want to select have the same value or different? How about the checkboxes to exclude?

My first instinct is to try attribute selectors (see the top few examples here: http://api.jquery.com/category/selectors/

I.E. $('input:checkbox[value=myvalue]') or similar.

Else you will possibly need to use .each() to test each value and set the checked attribute as required.


@Kerry: Thanks you pointed me in the right direction...

I am getting confused between IDs and Names. If I set the ID to the value (which is unique) and keep the names the same I can reference each checkbox and still get the posted array of values...


You'll be looking at something like:

$('input:checkbox').attr('checked', false).filter('[value=1],[value=2],[value=3]').attr('checked', true);

You could also do something like:

$('input:checkbox').attr('checked', function () {
    if (this.value == 1 || this.value == 2 || this.value == 3) {
        return true;
    } else { 
        return false;
    }
});

If you've got the values you want selected in an array, you can do some magic as follows:

var toCheck = [1,2,3];
$('input:checkbox').attr('checked', false).filter('[value=' + toCheck.join("],[value=") + ']').attr('checked', true);

Which will give you the same as the first example.

These will all untick all tickboxes that don't match the ticked selector; but can obviously be easily adapted.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜