'How can I disable other checkboxes(Dynamically Created) if I checked one?
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 class="PillList-item">
<input id="Check" type="CheckBox" name="@item.ProductID"/>
<span class="PillList-label" >
@item.Products
<span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
</span>
</label>
}
}
Solution 1:[1]
Try to use the following code:
@section Scripts{
<script>
$(document).ready(function () {
$('input:checkbox').click(function () {
$('input:checkbox').not(this).prop('checked', false);
});
});
</script>
}
Solution 2:[2]
First Update the dynamic checkbox code with addition of 'chkInfo' as class value i.e.
foreach (var item in ViewBag.Products)
{
<label class="PillList-item">
<input id="Check" type="CheckBox" name="@item.ProductID" class="chkInfo" onclick="Javascript:{UncheckAll_js(this)}"/>
<span class="PillList-label" >
@item.Products
<span class="Icon Icon--checkLight Icon--smallest"><i class="fa fa-check"></i></span>
</span>
</label>
}
Then using Java Script as below uncheck all the unwanted checkboxes i.e.
// Global variable to access jQuery method from JavaScript method.
var uncheckAll_jq;
// jQuery method goes here.
$(document).ready(function()
{
// This method will disable all the check boxes except the one which is checked
uncheckAll_jq = function UncheckAll(currentCheckBox)
{
// First unchecheck all
$(".chkInfo").removeAttr('checked');
// Then check your target checkbox as already checked.
$(currentCheckBox).attr("checked", true);
}
});
// JavaScript codes goes here.
function UncheckAll_js(currentCheckBox_info)
{
// Invoke jQuery Method.
UncheckAll_jq(currentCheckBox_info);
}
Hope this helps!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yiyi You |
| Solution 2 |
