I have 7 or 8 checkboxes. When a user clicks on a button, I want to check to see if atleast one of the checkboxes is checked. Otherwise I want to alert the user to check a box.
So far this is the code I wrote. Any further help from here is greatly appreciated. Thanks
function check() {
var checkboxCollection = document.getElementById('<%=CheckBoxListRuns.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
//Here I need to put a validation check.
}
}
}
Now, eventhough one checkbox is checked, I get the alert message saying “click atleast one checkbox”. I am sure I am doing something wrong in the return statuement
function PerformChecks() {
var vartextboxEOM = document.getElementById('<%= TextBoxPeriod.ClientID%>').value;
var vardropdownEOM = document.getElementById('<%= DropDownListEOMDates.ClientID %>');
//This is first check
if (vartextboxEOM == "" && vardropdownEOM.style.visibility == "hidden") {
alert("Enter/Pick the date from textbox");
}
else { //This is second check
var checkboxCollection = document.getElementById('<%=CheckBoxListInstruments.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].checked)
return;
else
alert("Please select at least one checkbox");
return;
}
}
I did exactly the way you said. Now the I get the alert message saying fine. But it still does it’s default behaviour.
Basically I have handled two click events on this button. onclick and OnClientClick events.
First OnClientClick is being fired. that is where the Performchecks javascript function is launched. Though the alert message is showing up, the server event (ButtonRun_Click) is also being launched after OnClientClick. I need to stop this server event in case I get the alert message from OnClientClick.
Sadly no. You are doing it while you are still in the loop. as an else part of the if statement.
You need to instead show the alert after the for loop is finished, since that is where you will end up if none of the checkboxes are found to be checked.
function PerformChecks() {
var vartextboxEOM = document.getElementById('<%= TextBoxPeriod.ClientID%>').value;
var vardropdownEOM = document.getElementById('<%= DropDownListEOMDates.ClientID %>');
//This is first check
if (vartextboxEOM == "" && vardropdownEOM.style.visibility == "hidden") {
alert("Enter/Pick the date from textbox");
}
else { //This is second check
var checkboxCollection = document.getElementById('<%=CheckBoxListInstruments.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].checked)
return;
}
window.alert("Please check atleast one checkbox");
}
}