[SOLVED]Referencing form arrays using JavaScript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

[SOLVED]Referencing form arrays using JavaScript

Post by jayshields »

Right. Say I've got a form like this:

Code: Select all

 
<form onSubmit="return confirmDeletions();">
  <input type="checkbox" name="del[]" id="del[]" />
  <input type="checkbox" name="del[]" id="del[]" />
  <input type="submit" />
</form>
 
And confirmDeletions() looks like this:

Code: Select all

 
function confirmDeletions() {
  var del = Array(document.getElementById('del[]'));
  var conf = false;
  alert('length: ' + del.length);
 
  for(var x=0; x < del.length; x++)
  {
    if(del[x].value != null)
    {
      alert(del[x].value);
      conf = true;
    }
  }
 
  if(conf == true)
    return confirm('Are you sure you want to delete the selected waiters?');
 
  return true;
}
 
Currently it is telling me that length is 1, the value of the only element is "on" and then asking me to confirm.

I know that I am grabbing the array of checkboxes incorrectly (because the length should be 2), can someone point me in the right direction? Google brings up nothing except for how to handle the document.forms array and the elements array.
Last edited by jayshields on Mon Aug 04, 2008 1:43 pm, edited 1 time in total.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: Referencing form arrays using JavaScript

Post by jayshields »

Ok, I've sorted it out now.

Here it is:

Code: Select all

<form id="whatever" onSubmit="return confirmDeletions();">
  <input type="checkbox" name="del[]" />
  <input type="checkbox" name="del[]" />
  <input type="submit" />
</form>

Code: Select all

 
function confirmDeletions() {
  var del = document.forms['whatever']['del[]'];
  var conf = false;
 
  for(var x=0; x < del.length; x++)
    if(del[x].checked == true)
      conf = true;
 
    if(conf == true)
      return confirm('Are you sure you want to submit some checked boxes?');
 
  return true;
}
I've just changed it around a bit to make the example more general, and I also missed out the name attribute in the form tag, but I'm not using that anymore since I discovered it's not valid XHTML strict...
Post Reply