I have several RadioButtonFor (razor) and I am trying to make a JQuery script that unchecks others buttons when you check another one.
I have a model with an array of booleans to pass to the Html Helper and printer names:
public class Mymodel
{
public List<PrinterModel> printers { get; set; }
public bool noDefault { get; set; }
}
My PrinterModel is as follows :
public class Printermodel
{
public bool selected { get; set; }
public string printerName { get; set; }
}
Which then gives in my view, :
@using (Html.BeginForm()
{
<div class="form-group">
for (var i = 0; i < Model.printers.Count(); i++)
{
@Html.RadioButtonFor(m => m.printers[i].selected, new { @class = "default" });
@Html.Label(Model.printers[i].printerName);
<br/>
}
@Html.RadioButtonFor(m=>m.noDefaultRadio, new { @class = "noDefault", @checked= "checked" });
@Html.Label("No default printer");
</div>
}
I know I can use .prop('checked', false) in JQuery to uncheck a radiobox, so I tried in the first play to uncheck the default button :
$('.default').change(function () {
if ($('.default:checked').length > 0) {
$('.noDefault').prop('checked', false);
}
else {
$('.noDefault').prop('checked', true);
}
});
This does nothing, but works for checkboxes, why?
Also, the @checked="checked" doesn't make the RadioButtonFor checked by default, and I've also tried @checked = true which doesn't work either.
Any ideas?
EDIT When trying to use name="default" as suggested, I see the following input when inscpecting the page in my navigator :
<input data-val="true" id="printers_0__primarySelected" name="printers[0].primarySelected" type="radio" value="{ disabled = disabled }"
Can you just make the radio buttons part of a group? What you are trying to do sounds like default behavior.
Can you add the
name = "printerGroup"(or similar) to your HTML attributes in the RadioButtonFor calls to group these together?UPDATE:
Stepping back, sounds like you want 1 radio button to be selected. You should be looking to have a selectedId or some identifier passed back to your controller once you submit. I would look to make the following changes.
Model
View
Inside your controller you can get the selectedId and do something with it, if 0 was passed in that would be the default (change as needed).