简体   繁体   中英

jQuery Selector For “Html.CheckBoxFor”

Is there a way using asp.net/jquery to toggle a div visibility when using a checkbox like this:

<%: Html.CheckBoxFor(m => m.Type) %>

I know how to do the jQuery part, but I'm not sure how to determine whether or not the box has been clicked or changed. Is there some sort of onChange or onClick I can add to this?

EDIT - Let me change this a bit...HOW can I assign an id to the Html.CheckBoxFor()??

You could subscribe for the .change() event and .toggle() the visibility of the div based on whether the checkbox has been checked or not:

$(function() {
    $('#mycheckbox').change(function() {
        var isChecked = $(this).is(':checked');
        $('#someDivId').toggle(isChecked);
    });
});

And you can see it in action here .

To identify this checkbox you could either assign it an unique id:

<%: Html.CheckBoxFor(m => m.Type, new { id = "mycheckbox" }) %>

or a class:

<%: Html.CheckBoxFor(m => m.Type, new { @class = "check" }) %>

and then adapt your jQuery selector.

Yes, there is an onclick/onchange event for most of html element.

Let assume your checkbox has an id="checkbox1", you can do the following

var myCheckBox = document.getElementById("checkbox1");
myCheckBox.addEventListener('change', function(){do something}, false);

See this question: get the generated clientid for a form field , this is my answer:

I use this helper:

public static partial class HtmlExtensions
{
    public static MvcHtmlString ClientIdFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(
              htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(
                  ExpressionHelper.GetExpressionText(expression)));
    }
}

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)

or in the script:

$(function() {
    $('#@Html.ClientIdFor(m=>m.Type)').change(function() {
        // Do stuff
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM