开发者

Modifying the contents of a page based on a "select" element

I currently have a page that allows a user to enter different types of database entries via a select("questions" for a survey), i.e. Multiple Choice, Text, Drop-down, etc. Each one atleast contains a textarea and 2 input type="text"s. Right now this is done by having 4 divs in the HTML, 3 of which are hidden via CSS ("display:none"). Then a JS action is hit on the select change, which 开发者_运维百科uses a switch statement to hide and unhide all the divs correctly. Form.onsubmit deletes all the divs except the currently selected one, as they all use the same names for their inputs.

Obviously this is incredibly inefficient and ugly. I think the correct way would be to create the elements using JS, something I suck at, and then when the user changes the select, remove the child div from the form and add the desired form div. However, I don't know how to do this.

I would greatly appreciate it if someone could show me how to go about my suggestion, or show how to do it better.

Thanks.


Actually your method doesn't sound too bad at all. One of two things I would call into question would be the reasoning for naming them all the same thing - if they really represent the same data, why not actually use the same form elements for all 4 sections?

The other thing I would want to improve is the need to remove anything from the DOM when the form submits. This not only adds complexity to your submission process, but it also prevents problems if the user hits the back button to try again.

I would not create/destroy elements every time the value is changed -- not only is this somewhat more inefficient, it is a pain to maintain, more susceptible to bugs, and will blow away any information the user has entered.

I think there are two main options which could improve this for you:

1) Keep the same fields

If the 4 types really do have 3 common fields each, why don't you have those in a section which never gets hidden, and have any only the information unique to each type in a special section which can be shown or hidden when the value of the SELECT element is changed.

2) Disable the fields that are hidden

Fields that are disabled are simply not sent to the server. Therefore, you can keep the same names on multiple elements, without having to delete them before submission, as long as you make sure only one is not disabled. I use a toggleDisabled method that will take an element and iterate over all children and all descendants recursively and disable or enable input/select/textarea elements. Then I can just pass in a single element and enable/disable all form elements. It would work perfectly for what you are trying to do - you would hide your DIV, then you would disable it. You would then show and enable the selected one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜