So I have a screen with multiple radio buttons. On initial page load, the page with radio button controls needs to be displayed regularly. But if selected and saved, on postback the radio button control needs to be disabled and not able to change. If the radio button control was not selected, then they should appear as normal.
This is my code.
<div id="divFood">
@foreach (var fruit in Model)
{
<input id="@fruit.Value" type="radio" name="Fruit" value="@fruit.Value"/>
<label for="@fruit.Value">@fruit.Text</label>
<br/>
}
@foreach (var dairy in Model.Dairy)
{
<input id="@dairy.Value" type="radio" name="Dairy" value="@dairy.Value"/>
<label for="@dairy.Value">@dairy.Text</label>
<br/>
}
@foreach (var veg in Model.Vegetable)
{
<input id="@veg.Value" type="radio" name="Veg" value="@veg.Value"/>
<label for="@veg.Value">@veg.Text</label>
<br/>
}
@foreach (var meat in Model.Meat)
{
<input id="@meat.Value" type="radio" name="Meat" value="@meat.Value"/>
<label for="@meat.Value">@meat.Text</label>
<br/>
}
</div>
My JQuery code is as follows. The issue is that my code only disables the selected radio button option rather than the radiobutton control. For example, if in Meat radio button, chicken option is selected, Only chicken gets disabled and not all other options of Meat. How do I fix it?
$(document).ready(function () {
$("#divFood input[type=radio]").each(function() {
if($(this).is(':checked')) {
$(this).attr('disabled', 'disabled');
}
});
});
2
Answers
I haven’t used jQuery in too long so unsure how to do it with JQ’s
filter
andeach
however with native dom api’s you can do something like the following.First we select all of the inputs, we filter the list by any that are checked. Next we take that filtered list and iterate it grabbing the
name
then we do a select of any elements which match thatname
and set the disabled property.This could be simplified a few ways, one way is you could wrap a
fieldset
around each group and just set that to disabled.Below is vanilla JS but should be adaptable to jQuery if necessary.
You can loop through checked radio button and then inside each loop get the name attribute of checked radio to disabled other radio with same name.
Demo Code :