fanfavorite
fanfavorite

Reputation: 5199

Building HTML Forms With Arrays

I have a form with elements like:

<div class="row1">
   <select name="someSelectField" multiple="multiple" class="selectList">
      <option value="1">1</option>          
      <option value="2">2</option>          
   </select>
   <input type="checkbox" name="checkboxField" class="checkboxField" value="1" /> checkbox</td>
</div>
<div class="row2">
   <select name="someSelectField" multiple="multiple" class="selectList">
      <option value="1">1</option>          
      <option value="2">2</option>          
   </select>
   <input type="checkbox" name="checkboxField" class="checkboxField" value="1" /> checkbox</td>
</div>

These will continue down the page. With lots of different rows of these same fields. There is no set rows as javascript is used to create more rows.

My question is, what should the value of each name attribute be, so that it stays grouped as arrays and can be referenced together? For example, if I use someSelectField[1], when the method is GET, the form sends it like someSelectField[1]=1&someSelectfield[1]=2 (if both are selected). I am looking for it to be someSelectField=1&someSelectfield=2, etc.

Any help would be appreciated. Thanks.

Upvotes: 2

Views: 623

Answers (1)

Dave L
Dave L

Reputation: 1634

Why don't you just give the controls unique names? If your javascript is capable of giving the divs indexed class names, you could just restructure the html as so:

<div class="row1">
   <select name="someSelectField1" multiple="multiple" class="selectList">
      <option value="1">1</option>          
      <option value="2">2</option>          
   </select>
   <input type="checkbox" name="checkboxField1" class="checkboxField" value="1" /> checkbox</td>
</div>
<div class="row2">
   <select name="someSelectField2" multiple="multiple" class="selectList">
      <option value="1">1</option>          
      <option value="2">2</option>          
   </select>
   <input type="checkbox" name="checkboxField2" class="checkboxField" value="1" /> checkbox</td>
</div>

This has the benefit of being server independent too since some frameworks parse html arrays really well and give you a proper array, and some just overwrite keys.

Your parsing might get a little messy on the back-end if you're allowed to remove elements from the middle instead of just from the end but it shouldn't be too bad. And if that is a concern you could write a simple jQuery script that would line all your names up again. Warning, untested code follows:

$("div[class^='row']").each(function(idx, value) {
    var $value = $(value);
    $value.find(".selectList").attr("name", "someSelectField"+(idx+1));
    $value.find(".checkboxField").attr("name", "checkboxField"+(idx+1));
});

Upvotes: 1

Related Questions