Skip to content


Handling HTML Checkboxes Array in JavaScript

This section contains a lot of Scripting material for your website.

Handling HTML Checkboxes Array in JavaScript

Postby Shahzad Butt » February 10th, 2009, 9:06 am

In web development, we face some situations where we need to check whether any option is selected or not from a number of checkboxes which are used as an Array. We can easily check this with the help of javascript, whether the user has selected any option or not.

HTML Code
Code: Select all
<form name="frmCheck" id="frmCheck" method="" action="">

<b>Select Color(s):</b><br />
<input type="checkbox" name="Color[]" value="Red" /> Red<br />
<input type="checkbox" name="Color[]" value="Blue" /> Blue<br />
<input type="checkbox" name="Color[]" value="Orange" /> Orange<br />
<input type="checkbox" name="Color[]" value="Yellow" /> Yellow<br />
<input type="checkbox" name="Color[]" value="Green" /> Green<br />

<input type="button" value="Check" onclick="checkSelection( );" />
</form>


Javascript Code:
Code: Select all
<script type="text/javascript">
<!--

function checkSelection( )
{
   var iLength = document.getElementsByName("Color[]").length;
   var bFlag   = false;

   for (var i = 0; i < iLength; i ++)
   {
      if (document.getElementsByName("Color[]")[i].checked == true)
      {
         bFlag = true;
         break;
      }
   }

   if (bFlag == false)
      alert("You havn't selected any Color.");
}

-->
</script>
Regards
Shahzad Butt
User avatar
Shahzad Butt
 
Posts: 32
Joined: July 9th, 2008, 11:16 am
Location: Pakistan

Return to Board index

Return to Java Script / VB Script

Who is online

Users browsing this forum: No registered users and 0 guests