开发者

Hide form field, but don't submit in JavaScript

I want to hide some form fields by default, and only reveal in groups them depending on a checkbox.

If a user shows some f开发者_StackOverflow社区ields, fills them in, but then rehides them using the checkbox, will the data submit anyway if the fields have something in them or should I empty them using JavaScript?


The fields will send anyway, but your service which is receiving the post should just look for the value of that checkbox and ignore the values at that point. Either that or you will need to clear the fields.


According to the html spec a field is submitted if it meets the following criteria:

  • It is contained in the form being submitted
  • It is of type input, select, button
  • It contains a non-blank name attribute
  • If it is of <input type="checkbox" or type="radio"/> it must be checked.

Visibility is unimportant. In fact there are many reasons why something may be invisible incluiding being off-screen. Some techniques such as honeypot fields require this.

So to fully answer your question, if some form interaction demands that you only submit what is visible, you can do one of the following:

  • Move "visible" elements to be children of the form (prefered way) move them to another parent when not visible (after animation hides them). This should be easiest way I think especially if using jquery. Remember for animations, move hidden elements around to appropriate parents, then animate. Furthermore hidden elements can be easily manipulated with minimal performance since the browser does not attempt to re-render them until they are made visible anyways.
  • Clear out data (lose user input)
  • Clear out names of input fields, and re-create the names when they are unhidden.

The third technique is a bit much. I'd do either first or 2nd depending on your specific needs with a preference given to the first.


To keep it short and sweet, use javascript to remove the field. This is easy and quick, and you won't have to extend your server side script to determine what went through. If you want too, store the removed html into a global var, so when they toggle the option the script's back. Hope this helps!


If the form is just getting visibly hidden, yes, the data will still submit despite having hidden them. You need to empty them via JS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜