javascript validation to check only one checkbox among multiple checkboxes

Suppose you have a page with the listing of all the users registered on your site. Every record has a check box with it to select that record . Client want that user can select only one record at a time from that list and user must select one record for further action. Now what to do . Don’t worry this is not so hard , you can found the solution on web for this or you can write your logic for this. But i am giving here so you can find it very easily.Here it is:

<script type=”text/javascript”>
function checkBoxValidationForSingle(checkBoxName)
{

var name=checkBoxName+’[]‘;
var hasChecked=false;
var chk=document.getElementsByName(name);
for(var i=0, c=0; i< chk.length ; i++)
{
if(chk[i].checked==true)
{
c++;
var cValue = chk[i].value;
hasChecked = true;
}
}
if(!hasChecked)
{
alert(’Please select checkBox’);
return false;
}else if(c > 1){
alert(’Please select only one checkbox’);
return false;
}else {
return cValue;
return true;
}
}
</script>

see live example

No related posts.

Leave a Reply

XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>