The Silicon Valley Code Camp web site used jQuery to do a lot of the page markup manipulation. Behind the scenes of course is ASP.NET MVC5 which has a lot of helper methods for things like Check Boxes and Radio Buttons. General purpose methods are nice (until they are not). I’m building a more sophisticated “Opt-Out” for the code camp site and have created a choice where the user can say they want “All Emails” or “Critical Emails”. I did not want to have a third choice for “No Emails” since say they don’t want all and they don’t want critical implies they don’t want any. Also, it does not make sense for the user to say they want both “All” and “Critical”. It’s a one or another, just like radio buttons.
Since I could not use radio buttons to make the behavior correct, I decided to do the validation logic in jQuery. Here is the short code that takes care of it (along with the ASP.NET MVC5 code for reference).
<script type="text/javascript"> $(document).ready(function() { // these are not quite radio buttons. want to be able to check them both off if you want, // but not allow both to be set. $('#EmailReceiveAllYears').change(function () { if ($('#EmailSendMinimalEmail').is(':checked')) { $('#EmailSendMinimalEmail').prop('checked', false); } }); $('#EmailSendMinimalEmail').change(function () { if ($('#EmailReceiveAllYears').is(':checked')) { $('#EmailReceiveAllYears').prop('checked', false); } }); }); </script>
And the ASP.NET MVC5 razor form:
@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.HiddenFor(a => a.RegisterUserInfoLoggedIn.AttendeesId)<div <span class="kwrd">class</span>=<span class="str">"important"</span>> <div <span class="kwrd">class</span>=<span class="str">"checkField"</span>> @Html.CheckBoxFor(m => m.EmailReceiveAllCurrentYear) @Html.LabelFor(m => m.EmailReceiveAllCurrentYear, <span class="str">"Receive mailings regarding this years event..."</span>) </div> <div <span class="kwrd">class</span>=<span class="str">"checkField"</span>> @Html.CheckBoxFor(m => m.EmailReceiveAllYears) @Html.LabelFor(m => m.EmailReceiveAllYears, <span class="str">"Receive all mailings regarding ..."</span>) </div> <div <span class="kwrd">class</span>=<span class="str">"checkField"</span>> @Html.CheckBoxFor(m => m.EmailSendMinimalEmail) @Html.LabelFor(m => m.EmailSendMinimalEmail, <span class="str">"Receive ONLY critical email ..."</span>) </div> <div <span class="kwrd">class</span>=<span class="str">"checkField"</span>> @Html.CheckBoxFor(m => m.EmailReceiveSponsorEmail) @Html.LabelFor(m => m.EmailReceiveSponsorEmail, <span class="str">"Receive emails from our sponsors. From ..."</span>) </div> </div> <div> <div> <input type=<span class="str">"submit"</span> <span class="kwrd">class</span>=<span class="str">"button magenta"</span> <span class="kwrd">value</span>=<span class="str">"Save Changes"</span> /> </div> </div>
}
HTH’s!