views:

102

answers:

5

Hi,

I have a form which has a lot of SELECTs. For various reasons, I'd like to only pass to the form the ones that are selected by the user. In other words, each SELECT is something like this:

<SELECT name=field001>
  <option value=-1>Please pick a value</option>
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
</SELECT>

Usually, only one or two will be selected at a time, and I'd like to only pass the selected ones to the form. I'm guessing I'd need to unset the inputs that are -1 in JavaScript, but I'm not sure how to do that, and also wonder if there might be a standard approach to this kind of thing.

Thanks,

Ben

+5  A: 

When you post a form it will send the values of every single control to the server. If you need to prevent this I think your best option is to overwrite the onSubmit action and redirect to a new instance of the same page placing only the information you want on the querystring.

Take in mind that this will increase your code complexity a LOT and will make it harder to maintain. My opinion is that you simply wont gain enough performance that will make your effort worth while, but that's up to you.

Sergio
+1 for the downsides and alternative
Michael Haren
+1  A: 

Like Sergio said, pass the selected items in a query string to a new instance of the same page.

Eppz
+1  A: 

This is not common.

If you really need it, then you can either do what @Sergio suggested or, actually remove the items you want to skip from the dom, or possibly mark them as disabled when you submit (though some browsers my do different things with disabled controls--you'd have to check).

This really isn't common. If you have so many selects that sending them is causing problems, you have too many selects.

The normal way to handle this is to use your magic value, "-1", to know when to ignore certain values on the server side.

Michael Haren
+2  A: 

I would always inspect each element regardless of the quantity, but especially because of the quantity. How else could you be sure the user didnt change something else? You said:

Usually, only one or two will be selected at a time

so right there you're not even 100% sure, eh? Experience has taught me to never trust what you're hoping might happen "usually" because it will often be the unexpected that nabs ya!

Interactive Development Corp
+1  A: 

assuming you only have one form add this script to your page:

document.forms[0].onsubmit = function(){
    var selects = this.getElementsByTagName('select');
    for ( var i = selects.length - 1; i>=0; i-- ) {
        if ( selects.item(i).value == -1 ) {
         selects.item(i).parentNode.removeChild(selects.item(i));
        }
    }
    return true;
}
Ramuns Usovs