简体   繁体   中英

Checkbox to enable or disable a list box

I have a checkbox on my ASP.NET MVC page that I create like:

<div>
    @Html.CheckBoxFor(m => m.allUsers, new { Name = "allUsersCheck" })
    @Html.LabelFor(m => m.allUsers)
</div>

I also have a listbox that I create with:

@Html.ListBoxFor(x => x.selectedUsers, Model.ListofUsers, new { style = "width:200px", size = 10, Id = "lbUsers" })

I have this following script (which I wrote to disable the listbox when my checkbox is checked. I can't understand why it doesn't work. Can someone point out what's wrong in my code please?

This script is in the same.cshtml page and not in the.js file:

<script >

    $(function () {
        $('#allUsersCheck').click(function () {
            $('#lbUsers').prop("disabled", $(this).prop('checked'));
        });
    });

</script>

Because you are using the Id selector of '#allUsersCheck'. The checkbox does not have an Id attribute unlike your list box(?).

@Html.CheckBoxFor(m => m.allUsers, new { Name = "allUsersCheck" })

Try the following with an Id attribute:

@Html.CheckBoxFor(m => m.allUsers, new { Name = "allUsersCheck", Id = "allUsersCheck" })

Ok. Took me a while to figure out the entire list of things I need to do.

Here's all I did to finally get it working.

  1. Firstly, I needed this jquery library being used.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  1. Then I had to create a function under the above jquery inclusion
<script type="text/javascript">

    $(function () {
        $("#allUsersCheck").change(function () {
            $("#lbUsers").find("option").prop("selected", this.checked)

        });
    });
</script>

In the above you'll see allUsersCheck is the checkbox element's id and lbUsers is the id for the ListBoxFor element.

  1. The next thing is, in my.cshtml I needed to use/create the listboxfor / checkbox elements. This is how I did it
      <b>Users </b><br />
      @Html.ListBoxFor(x => x.selectedUsers, Model.ListofUsers, new { style = "width:200px", size = 10, id = "lbUsers" })
      <br />


      <div>
           @Html.CheckBoxFor(m => m.allUsers, new { id = "allUsersCheck" })
           @Html.LabelFor(m => m.allUsers)
      </div>
 

I also used a bool flag as part of my model. allUsers is the flag. The bool flag was needed for something else in the controller code and not for UI reasons.

I am not sure if this is the best method. But this is the method I could get it working.

Thanks to the guys who helped me in this process get this working. Obviously not without them.

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