How to avoid sending input fields which are hidden by display:none to a server?

glaz666 picture glaz666 · Sep 3, 2009 · Viewed 75.5k times · Source

Imagine you have a form where you switch visibility of several fields. And if the field is not displayed you don't want its value to be in request.

How do you handle this situation?

Answer

karim79 picture karim79 · Sep 3, 2009

Setting a form element to disabled will stop it going to the server, e.g.:

<input disabled="disabled" type="text" name="test"/>

In javascript it would mean something like this:

var inputs = document.getElementsByTagName('input');
for(var i = 0;i < inputs.length; i++) {
    if(inputs[i].style.display == 'none') {
        inputs[i].disabled = true;
    }
}
document.forms[0].submit();

In jQuery:

   $('form > input:hidden').attr("disabled",true);
   $('form').submit();