Home > Blockchain >  How can I disable other checkboxes(Dynamically Created) if I checked one?
How can I disable other checkboxes(Dynamically Created) if I checked one?

Time:04-13

How can I disable other checkbox if I clicked one I..e dynamically created checkbox using "input type=checkbox"

@if (ViewBag.Products != null)

{

    foreach (var item in ViewBag.Products)

    {

        <label >

            <input id="Check" type="CheckBox" name="@item.ProductID"/>

            <span  >

                @item.Products

                <span ><i ></i></span>

 

            </span>

          

        </label>

 

    

    }

 

}

CodePudding user response:

Try to use the following code:

@section Scripts{
        <script>
            $(document).ready(function () {
                $('input:checkbox').click(function () {
                    $('input:checkbox').not(this).prop('checked', false);
                });
            });
           
        </script>
    } 

CodePudding user response:

First Update the dynamic checkbox code with addition of 'chkInfo' as class value i.e.

foreach (var item in ViewBag.Products)
{
    <label >

        <input id="Check" type="CheckBox" name="@item.ProductID"  click="Javascript:{UncheckAll(this)}"/>

        <span  >

            @item.Products

            <span ><i ></i></span>

         </span>
    </label>
}

Then using Java Script as below uncheck all the unwanted checkboxes i.e.

$(document).ready(function() 
{
    // This method will disable all the check boxes except the one which is checked
    function UncheckAll(currentCheckBox) 
    {
        // First unchecheck all
        $(".chkInfo").removeAttr('checked');

        // Then check your target checkbox as already checked.
        $(currentCheckBox).attr("checked", true);
    }
});

Hope this helps!!

  • Related