0

I'm trying to create a string to pass to a PHP file with numerous variables in it. The Javascript code goes through an array of variables - the names of which correspond to checkboxes in a form on the page. If the name of the variable in the array has been checked in the form below then it adds the name of the variable to the string that gets posted to the PHP file. Here's the code:

 var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
   var sendStr = "";

   for (var i in datesStr) {

   if(document.swapOptions.datesStr[i].checked == true) {
     sendStr = sendStr+"&to"+i+"="+datesStr[i];
   }

   }

But for some reason it has a problem when I put the variable into the document.swapOptions line. I've also tried this but it doesn't work:

var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
   var sendStr = "";
var intermedDatesStr = "";

   for (var i in datesStr) {

   intermedDatesStr = document.swapOptions.datesStr[i];

   if(intermedDatesStr.checked == true) {
     sendStr = sendStr+"&to"+i+"="+datesStr[i];
   } 
   }

But it doesn't work either. I think the browser's looking for an object in the form called "intermedDatesStr". Is there any way to reference the object held be the variable value? Any help here would be most appreciated!

Thanks, Ben

2
  • What do you mean be "doesn't work" exactly? If it's a Javascript problem, please show the finished generated HTML rather than the PHP source code, it makes debugging easier. Commented Nov 1, 2010 at 12:00
  • Sorry that wasn't clear enough, I've made those adjustments now. Commented Nov 1, 2010 at 12:04

1 Answer 1

1

You need to use bracket notation when accessing properties dynamically like this:

var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
var sendStr = "";
var intermedDatesStr = "";
for (var i=0; i<datesStr.length; i++) {
  if(document.swapOptions[datesStr[i]].checked == true) {
    sendStr = sendStr+"&to"+i+"="+datesStr[i];
  } 
}

This accessed the properties like this:

document.swapOptions["L2010L04L01"]
//which is the same as:
document.swapOptions.L2010L04L01

The other change is using a normal for loop, a for...in loop is not the proper way to iterate through the array, you'll get other inherited properties and not necessarily the order you expect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.