开发者

Checking checkboxes using javascript when there id's have a certain character within

I need to check a certain selection of checkboxes using JavaScript. All these checkboxes have the letter a at the beginning of the id and other checkboxes have a different letter.I also don't know how many of these checkboxes there will be since they are created dynamically

<input type="checkbox" id="a1" />

Now if I click on a button a JavaScript function is called and these checkboxes with letter a at beginning of id's should be checked, is this possible and how?

Is there something that can be used in conjunction with document.getElemen开发者_JAVA技巧tById('a').checked?


You can get the checkboxes and loop through them, like this:

var checks = document.getElementsByTagName('input');
for(var i = 0, cb; cb = checks[i]; i++) {
   if(cb.type.toLowerCase() == 'checkbox' && cb.id && cb.id.charAt(0) == 'a')
     cb.checked = true;
}

You can give it a try here

Edit: a bit cleaner to use .charAt(), good call and thanks Tim!


It is better to specify a class 'a' to the inputs with id ="a*' and then select all the checkboxes with that specific class using jQuery

example:

<input type="checkbox" id="a1" class="a" />

code in jQuery:

$(".myClass").attr('checked', true);

I hope this helps and if you don't mind using jQuery


Newer browsers (IE8, Firefox, Chrome, Opera) have querySelectorAll() which will allow you to do something like this:

var chks = document.querySelectorAll("input[type=checkbox][id^=a]");

This would find all elements with type="checkbox" and an id attribute that starts with the letter a. For older browsers, you'd have to use something like Nick Craver's method. Alternatively, you could use something like Sizzle, which is the CSS selector engine used in jQuery.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜