Link to home
Start Free TrialLog in
Avatar of bganoush
bganoush

asked on

Dynamic list of checkboxes none, one or many?

Hi,

I have a form that is generated using entries from a database such that there may be a set of checkboxes generated. To get the values of the checkboxes, I have the following code:

function atLeastOneChecked(checklist)
{
   var isChecked = false;
   for (i = 0; i < field.length; i++)
   {
      if (field[i].checked)
      {
         isChecked = true;
         break;
      }
   }
   return isChecked;
}

if (!atLeastOneChecked(document.myform.myboxes))
{
   alert ("You must select at least one checkbox to continue...");
   return false;
}

The checkboxes are set up like this:

<input type=checkbox id="${DB_ID}" db_id="${DB_ID}" name="myboxes" value="${DB_VAL}"  ${DB_CHK}>

NOTE: The strings that start with the "$" sign are replaced server-side, the client browser will see something like this:

<input type=checkbox id="200710010001" db_id="200710010001" name="myboxes" value="Y">
<input type=checkbox id="200710010002" db_id="200710010002" name="myboxes" value="N" checked>
<input type=checkbox id="200710010003" db_id="200710010003" name="myboxes" value="N">
<input type=checkbox id="200710010004" db_id="200710010004" name="myboxes" value="Y">

Now my question is this...

When my form only contains one checkbox (or none), then the function "atLeastOneCheckbox" doesn't work...  How can I make it work for when there is no checkboxes in my form (returning false) or when there is only one checkbox (returning the "checked" flag of the checkbox)?

Avatar of Pravin Asar
Pravin Asar
Flag of United States of America image

function CheckForSelection (radValues) {
   var retCode = false;
   for (var rx=0; rx < radValues.length; rx++)  {
      if (radValues[rx].checked) {
         retCode = true;
         break;
      }
   }
   return (retCode);
}

// Scan the form for CheckBox
// Make Sure it is checked.
function validatePage(form)
{
   var elems = form.elements;
   for (var ix=0; ix < elems.length; ix++) {
         var elem = elems[ix];
         if (elem.type.match('checkbox')) {
              if (!CheckForSelection(elem)) { return false;}
         }
   }
}

<form onsubmit="return  validatePage(this);">
</form>
The code I posted is very generic. Scans the form for presence of checkBoxes.

Returns false, if the no option is selected
See the working code at

http://www.javascriptjournal.com/tutorials/checkValidate.htm

Feel free to see source code.
Avatar of bganoush
bganoush

ASKER


Thanks... I was hoping not having to go through ALL items in the list because my forms can get pretty long.

Is there a way to look at the object returned from "document.myform.mylist" to check if it is an array or if it even exists?

// Exists ???
if (!document.myform.mylist)  { alert ('Null Object'); }

// Is an Object

var arMyArray = new Array(10)
alert ( typeof(arMyArray));

// There is no ready-made function.
// You can look at the contructor of an object and determine the object type.


function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

I tried that.. the "constructor" thing but for some reason it doesn't work in IE.. I get an error on the page.

The exists thing is a no-brainer...  Again, hoping to have a one-stop solution.

So far I have this:

if (mylist == null)
   alert ("There are no checkboxes");
else if (mylist.type == 'checkbox')
   alert ("There is only one item, a checkbox");
else
  alert ("If the other two don't pan out, then let's assume it's an array: " + mylist.length);

This seems to work for me but I wasn't sure if this would be a good solution for all browsers, etc...


Here's an example I tried...   The two functions isArray1 and isArray2 don't work... I.E. says "constructor is null or not an object"...

<HTML>
<SCRIPT>
function isArray1(obj)
{
      if (obj.constructor.toString().indexOf("Array") == -1)
            return false;
      else
            return true;
}

function isArray2(obj)
{
      return (obj.constructor == Array);
}

function doCheck(theItem)
{
      if (theItem == null)
            alert ("null is '" + (theItem == null) + "'");
      else
      {
            var values = "";
            if (theItem.type == "checkbox")
            {
                  if (theItem.checked)
                        values = theItem.value;
            }
            else
            {
                  for (i = 0; i < theItem.length; i ++)
                  {
                        if (theItem[i].checked)
                              values += theItem[i].value + " ";
                  }
            }
            alert ("type is '" + theItem.type + "' and typeof is '" + typeof(theItem) + "' and null is '" + (theItem == null)
                  + "'\n\nValue(s): '" + values + "'");

            alert ("isArray1 is '" + isArray1(theItem) + "'");
            alert ("isArray2 is '" + isArray2(theItem) + "'");
      }
}
</SCRIPT>
<BODY>
<FORM name=myform>

<INPUT type=checkbox name=mylist id=1 value="Y"><LABEL FOR=1> Multi 1 </LABEL><BR>
<INPUT type=checkbox name=mylist id=2 value="N"><LABEL FOR=2> Multi 2 </LABEL><BR>
<INPUT type=checkbox name=mylist id=3 value="?"><LABEL FOR=3> Multi 3 </LABEL><BR>
<INPUT type=checkbox name=mylist id=4 value="X"><LABEL FOR=4> Multi 4 </LABEL><BR><BR>

<INPUT type=checkbox name=myone id=a value="AAA"><LABEL FOR=a> Single a </LABEL><BR><BR>

<!-- INPUT type=checkbox name=mynone id=none value="NADA" --><LABEL FOR=none> none </LABEL><BR><BR>

<input type=button id=sub1 value="Check List" onClick="doCheck(document.myform.mylist);">&nbsp;&nbsp;&nbsp;&nbsp;
<input type=button id=sub1 value="Check One" onClick="doCheck(document.myform.myone);">&nbsp;&nbsp;&nbsp;&nbsp;
<input type=button id=sub1 value="Check None" onClick="doCheck(document.myform.mynone);"><BR><BR><BR>

</FORM>
</BODY>
</HTML>
Look the following code .

This one shows the function/functions to get checkbox input elements and
<html>

<head>

<script type="text/javascript">
function atLeastOneChecked(formName, checkname)
{
   var isChecked = false;
   // Get the Form Elements with the supplied checkname

   var field = document.forms[formName].elements[checkname];
   if (field) { alert ('Element(s) not found : document.' +
                            formName + '.' + checkName);
   for (i = 0; i < field.length; i++)
   {
      if (field[i].checked)
      {
         isChecked = true;
         break;
      }
   }
   return isChecked;
}


function GetFormElements() {
      var form = document.forms["myform"];
      var elems = form.elements;
      var lastName = 'xxxxx';
      for(var ix=0; ix < elems.length; ix++) {
            if (elems[ix].type.match('checkbox')) {
                  if (!lastName.match(elems[ix].name)) {
                        lastName = elems[ix].name;
                        if (!atLeastOneChecked('myform', elems[ix].name)) {
                        alert ('For checkbox field named ' + elems[ix].name + ' no option is checked');
                        }
                  }
            }
      }
}
</script>

</head>

<body>
<pre>
<p>Get the all checkbox elements in the form </p>
<p>Check at least one option for a checkbox is Checked </p>
<FORM name=myform>
<INPUT type=checkbox name=mylist id=1 value="Y"><LABEL FOR=1> Multi 1 </LABEL><BR>
<INPUT type=checkbox name=mylist id=2 value="N"><LABEL FOR=2> Multi 2 </LABEL><BR>
<INPUT type=checkbox name=mylist id=3 value="?"><LABEL FOR=3> Multi 3 </LABEL><BR>
<INPUT type=checkbox name=mylist id=4 value="X"><LABEL FOR=4> Multi 4 </LABEL><BR><BR>
<input type="button" value="Get mylist elements" onclick="GetFormElements();">
</FORM>
</body>

</html>


Yes but you see the problem is not the implementation of MULTIPLE checkboxes.. But if you change the number of checkboxes to only one, then it doesn't work...  Even worse when there are NO checkboxes.

For instance, in your code, remove three of the checkboxes from your form and leave only one... then your code will complain that no checkboxes are clicked, no matter how many are actually used...

By the way, this line in your code is wrong:

   if (field) { alert ('Element(s) not found : document.' +
                            formName + '.' + checkName);

The "{" is not closed and do you really want to check if (field) or if (field == null)?

ASKER CERTIFIED SOLUTION
Avatar of Pravin Asar
Pravin Asar
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial