How can I change my checkbox to radio buttons?

2.1k Views Asked by At

So, I want to change my checkbox, that has checked and unchecked state to radio buttons that say, Yes (checked) or No (unchecked).

Here's what I did for the checkbox:

In my view:

@Html.CheckBoxUi("PerpendicularCheckbox",@H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", @class = "type-style-paragraph" })

js:

$('input:checkbox[name=PerpendicularCheckbox]').on({
                "change": function () {
                    if (getUpdate()) {
                        var $this = $(this);
                        if (($this).is(':checked'))
                            $("ul li button").click();
                    }
                }
            });

            if (!Perpendicular) {                
                $("#PerpendicularCheckbox").prop("checked", false);
            }
            else {               
                $("#PerpendicularCheckbox").prop("checked", true);
            }

I was wondering what would I need to change it to radio buttons, yes and no options, using html extension in asp.net mvc?

EDIT:

My loosy attempt at radio buttons:

 @Html.RadioButtonForUi("PerpendicularCheckbox",@H.GetString("IsPerpendicular"), null, new { style = "margin-right:10px", @class = "type-style-paragraph" })



 $('input:radio[name=PerpendicularCheckbox]').on({
                    "change": function () {
                        if (getUpdate()) {
                            var $this = $(this);
                            if (($this).is(':checked'))
                                $("ul li button").click();
                        }
                    }
                });

RadioButtonForUi :

 public static MvcHtmlString RadioButtonForUi<TModel, TProperty>(
          this HtmlHelper<TModel> htmlHelper,
          Expression<Func<TModel, TProperty>> expression,
          string name,
          bool IsEnable,
          bool IsChecked,
          object onchange = null,
          string className = "",
          bool isRequreid = true

        ) {etc.....}
2

There are 2 best solutions below

0
On

Here is a tested sample:

      <div class="form-group">
        @Html.LabelFor(model => model.SaleOfPropertyPurchase, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, true, new { id = "SaleOfPropertyPurchase-true" }) Yes
                @Html.RadioButtonFor(model => model.SaleOfPropertyPurchase, false, new { id = "SaleOfPropertyPurchase-false" }) No
                @Html.ValidationMessageFor(model => model.SaleOfPropertyPurchase, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

Here is some sample jquery that reacts to the radio button click, and also sets up initial display on the form:

    @Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(function () {
        $('#CurrentPropertyOwner-true').on('change', function () {
            $('#CurrentProperty').show();
        });
    });
    $(function () {
        $('#CurrentPropertyOwner-false').on('change', function () {
            $('#CurrentProperty').hide();
        });
    });

    $(document).ready(function () {
        var ischecked = $('#CurrentPropertyOwner-true').is(':checked')
        if (ischecked == true) {
            $('#CurrentProperty').show();
        }
        var ischecked = $('#CurrentPropertyOwner-false').is(':checked')
        if (ischecked == true) {
            $('#CurrentProperty').hide();
        }
    });
</script>
0
On

You need to render two radio buttons for the property, one with the value of "True" and the other with the value of "False" so the selected value can be bound to a boolean value

You custom html helper would need to be

namespace YourAssembly.Html
{
  public static class MyHelpers
  {
    public static MvcHtmlString BooleanButtonsFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
    {
      ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
      string name = ExpressionHelper.GetExpressionText(expression);
      StringBuilder html = new StringBuilder();
      // Yes button
      string id = string.Format("{0}-yes", name);
      html.Append(helper.RadioButtonFor(expression, "True", new { id = id }));
      html.Append(helper.Label(id, "Yes"));
      // No button
      id = string.Format("{0}-no", name);
      html.Append(helper.RadioButtonFor(expression, "False", new { id = id }));
      html.Append(helper.Label(id, "No"));
      // enclode in a div for easier styling with css
      TagBuilder div = new TagBuilder("div");
      div.AddCssClass("radiobuttongroup");
      div.InnerHtml = html.ToString();
      return MvcHtmlString.Create(div.ToString());
    }
  }
}

then add a reference to the <namespaces> section of web.config

<add namespace="YourAssembly.Html "/>

and use it in the view

@Html.BooleanButtonsFor(m => m.YourBoolProperty)