简体   繁体   中英

Need to check all radio boxes on a page using javascript

I need to use javascript to check all radio boxes with a certain ID on a page. The radio buttons all have different names, and are grouped by 3, one for approve, one for deny, one for review...

<input type=radio name='21' value='approved' id='approved' title='Approve'>
<input type=radio name='21' value='denied' id='denied' title='Deny'>
<input type=radio name='21' value='review' id='review' checked title='Do nothing right now'>

...and so on. I've searched on this site and all over the googles, not really finding a solution that works for me. I have another set of radio buttons on top of the page, that I want to use to control the others, so if I click the "approve" radio up top, all the approve radios are selected, deny does all the denied radio boxes on the page etc.

I am using an onclick on the top radio buttonset to fire a javascript function, but I've no idea what to tell the function to do. I assume that jquery would be able to do this nicely, but cannot seem to come up with the code to do so.

Try a click function on all radio and update the selection based on its value. See below,

//   v--- Refined the selector as you want this to happen only when clicking on the 
//        controller radio options.
$('.controller:radio').click(function () {
    $(':radio[value=' + this.value + ']')).prop('checked', true);
});

DEMO: http://jsfiddle.net/KvdNq/

What I would do is actually create the groups within separate DIVS. Then you can loop through all the radios within that particular div and dont need to care about what the IDS are for the respective Radio Buttons.

<div id="group1">
    <input type="checkbox" value="group1"/> Check all in this group
    <input type = "radio" value="xx" />
    <input type="radio" value="yy" />
</div>

Now you can simply create a function that takes the value of the checkbox, then loops through the matching div, checking all the RADIO BUTTONS within it. Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM