Tuesday, April 21, 2015

checkbox toggle only work once

http://stackoverflow.com/questions/29779113/asp-net-mvc-checkbox-jquery-toggle-only-work-once

if do not use Html.IdFor the it would not work.

<script type="text/javascript">
     $(function() {
      $('#@(Html.IdFor(model => model.IsActive ))').change(function() {
          $('#ShowHideMe').toggle($(this).is(':checked'));
      });
  });
</script>

using System;
using System.Linq;
namespace checkbox.Models
{
    public class Person
    {
        public bool IsActive { get; set; }
        public string Email { get; set; }
    
    
    }
}

@model checkbox.Models.Person

@Scripts.Render("~/bundles/jquery")

@Scripts.Render("~/bundles/jqueryval")


@using (Html.BeginForm())

{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <h4>Person</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
     
     
        <div id="myCheckbox" class="form-group">
            @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.IsActive)
                    @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div id="ShowHideMe" class="form-group">

            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

         <div class="form-group">

            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

No comments:

Post a Comment