Checkbox validation - at least one selected
20,579
Solution 1
var all=document.getElementById('holiDay');
In HTML IDs should be unique, so getElementById will only return 1 element. Perhaps you could try getElementsByTagName - http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx ?
Something like...
function check_checkboxes()
{
var c = document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {return true}
}
}
return false;
}
and change your Validate function to...
function Validate()
{
if(!check_checkboxes())
{
alert("Please identify what warehouses comply:");
return false;
}
return true;
}
Solution 2
Select at least one check box using jqQery. Try the following code.
$('input[type="checkbox"][name="class"]').on('change', function () {
var getArrVal = $('input[type="checkbox"][name="class"]:checked').map(function () {
return this.value;
}).toArray();
if (getArrVal.length) {
//execute the code
} else {
$(this).prop("checked", true);
alert("Select at least one column");
return false;
}
;
});
Author by
Some Java Guy
I did Java/J2EE for long time, now AWS architecture.
Updated on November 01, 2020Comments
-
Some Java Guy over 3 years
I have number of checkboxes and another checkbox for "Select All"
I want to check if the user has selected at least one checkbox. Need modification in javascript
<script language="Javascript"> function doSubmit(){ function check_checkboxes() { checked=false; var c = document.getElementsByTagName('INPUT'); for (var i = 1; i < c.length; i++) { if (c[i].type == 'checkbox') { if (c[i].checked) { return true} else {alert("Please identify what warehouses comply:"); } } } //if I place my struts action here..its not working? } document.holiDay.command.value= 'addingApp'; //My Struts action if something checked. document.holiDay.submit(); }