I'm working on a MVC program.
I'm using Razor language in a View to display a list of Projects (from a Database through Controller/Model) with CheckBoxFor :
for (int i = 0; i < Model.ProjectList.Count; i++)
{
@Html.HiddenFor(m => m.ProjectList[i].Id)
<li>@Html.CheckBoxFor(m => m.ProjectList[i].IsChecked,
new { id = "projectList_" + i, className = "CheckBoxProject" })
@Model.ProjectList[i].Name</li>
}
This part works fine.
I would like to add another CheckBox to uncheck and disable the previous ChekBoxFor and to prevent them to be checked. I tried to do this with some JavaScript put at the end of the View:
<input type="checkbox" id="SetBox" value="SetBox" onclick="CheckBoxState(this);">
<script type="text/javascript" onload="loaded=1">
function CheckBoxState(elementRef) {
document.querySelectorAll('.CheckBoxProject').checked = false;
document.querySelectorAll('.CheckBoxProject').disabled = true;
};
So if I understand what I have done, the "onclick" should call the Javascript function called "CheckBoxState" . Then grab all the CheckBoxFor having the className CheckBoxProject , uncheck and disable them.
When I'm trying it in Firefox, nothing happens when I check the last CheckBox and the page inspector shows a warning something like (is not in english) : failed to load script where the source is " http://localhost:..../browserLink "
I'm not sure how to tell to the View that i'm using Javascript and if Razor language is able to works with Javascript .
I tried different ways to code the JavaScript depending of what i found on StackOverflow and after several failure i resign myself to ask...
Finnally i found something that works with jQuery (that i didn't know) :
<input type="checkbox" id="SetBox"> <label>Uncheck and disable other Checkbox</label>
<script type="text/javascript">
// Call function when the element with the id = SetBox is clicked
$('#SetBox').click(function(){
var SetBox = document.getElementById("SetBox");
if (SetBox.checked)
{
// select all checkbox (even SetBox) and unchecked + disabled them
$('input:checkbox').prop('checked', false);
$('input:checkbox').prop('disabled', true);
// select only SetBox and check + enable it.
$('#SetBox').prop('checked', true);
$('#SetBox').prop('disabled', false);
}
else
{
// Make all checkbox available if SetBox is unchecked.
$('input:checkbox').prop('disabled', false);
}
});
It works with Html.CheckBoxFor().
I still have the warning : failed to load script where the source is " http://localhost:..../browserLink " But it seems it doesn't matter.
I hope this can help someone later.
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.