Checkbox to enable or disable a list box

你。 提交于 2021-01-28 05:49:18

问题


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>

回答1:


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" })



回答2:


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.



来源:https://stackoverflow.com/questions/63070355/checkbox-to-enable-or-disable-a-list-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!