I have a list of radio group that need to be checked by user.
<div><input type='radio' class='radio_m' name='1-a' /></div>
<div><input type='radio' class='radio_m' name='1-a' /></div>
<div><input type='radio' class='radio_m' name='2-a' /></div>
<div><input type='radio' class='radio_m' name='2-a' /></div>
User need to check at least one radio in each radio group. If not checked, all div which has same radio name will be flagged (change background-color to red)
This is my current script
$(form).find("div .radio_m").each(function(i){
var _this = $(this);
var ct_checked = 0;
_this.each(function(c){
if(_this.is(':checked') == false){
_this.closest("div").css("background-color","#F3A3A3");
}
else{
_this.closest("div").css("background-color","transparent");
}
});
});
My script only change the div with current checked radio. How do I target div which has radios with same name?
Ex:
- If user check radio with name
1-a
, all div (div 1 and 2) which has radio name1-a
will be transparent and other div (div 3 and 4) will be red
Any help is greatly appreciated
2
Answers
To find all the parent divs of radios with matching
name=
use attribute selector, eg:Although the method is "closest", if applied to a number of elements,
closest
will return the closest-parent of each of them (separately), giving exactly what you need.In addition, rather than loop through every radio, only loop through those that are already selected and then find matching radios and apply to their parents, eg:
Updated snippet:
To answer your question, this JSFiddle might help:
https://jsfiddle.net/jannunen/8otmxzLq/
What the code does, it listens for radio button clicks,
then counts if the group has more than 0 buttons clicked,
otherwise it changes the bg.
Try always keep your problem description so that it is concise,
now the JS you provided assumes that HTML has form tag in it.
Hope this helps.