Reputation: 1
I have tried so many options, but nothing has worked.
The main problem is that I have so many check boxes all are generated through php loop, so they have same name and id. I want to check that on submit of that form that at least one should be checked. I have tried so many function so not sure which should be pasted here. So it is better that some one suggest me some fresh answer.
function Validate_Checkbox()
{
var chks=document.getElementsByTagName('input');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please select at least one checkbox..!");
return false;
}
return true;
}
It is called as onsubmit="return Validate_Checkbox()"
in form tag.
Basically I am looking for a JavaScript function.
Upvotes: 0
Views: 3105
Reputation: 16786
Why just check it on submit? I wrote a function using Mootools that is called onchange on each checkbox and checks every checkbox in the same div. If there is no other checkbox checked the user can not uncheck the last checked checkbox.
<input type='checkbox' onChange='validateCheckboxes(this)' name='name' value='val' >
function validateCheckboxes(elem){
var checked = elem.checked;
elem.getParent().getElements("input[type=checkbox]").each(function(e){checked += e.checked});
if(checked == 0){
elem.checked = 1;
}
}
Upvotes: 0
Reputation: 34556
Well your code is OK for the purpose you describe. It could be shorter, but there's no obvious issues with it.
Shortened version
function validate_checkbox() {
var cbs = document.getElementsByTagName('input');
for (var i=0, len = cbs.length; i < len; i++)
if (cbs[i].type.toLowerCase() == 'checkbox' && cbs[i].checked)
return true;
alert("Please check at least one checkbox");
return false;
}
Even shorter version (if you don't care about old IEs)
function validate_checkbox() {
var checked = document.querySelectorAll('input[type=checkbox]:checked').length;
if (!checked) alert("Please select at least one checkbox");
return !!checked;
}
Notes:
1) IDs must be unique - you cannot repeat IDs across multiple elements
2) In JavaScript, it's better (for reasons that are beyond the scope of this post) to put opening curly braces on the same line, not next
3) Avoid capitalising functions unless you plan to instantiate them
Upvotes: 2
Reputation: 534
function seems to be fine. Are you sure it gets called? Try to debug it using firefox "Firebug". Open firebug->script and then put break point on this function.
Upvotes: 0
Reputation: 13956
your code will fail if you have other type of input like text
or submit
button. First you have to check if that is check box.
if (chks[i].type=="checkbox" && chks[i].checked)
Or thing will be easier if you use jQuery
if ($('input:checked').length < 1){
//Nothing checked
}
Upvotes: 0