简体   繁体   中英

Dynamic form submission using javascript - how to elegant code?

Here is the problem:

My page displays a set of items. Each item has a check box associated to it (which is part of a form). User might check any of these check boxes and press 'Delete' button. The same page also has a 'Upload' button which would upload an excel sheet of items. At the moment, my form action sumbits to say : "xyzAction" and I have two different handlers (analogous to Struts Action) - one for deletion of stores and other for uploading stores.

I am told that the best way to do this is to rely on javascript by doing one of these: 1)) Switching form action on press of upload and delete buttons - there by invoke different actions. 2) Use a hidden variable "act" to set it to delete / upload and submit to a single form. The server side action would take care of identifying the act and forwarding to the corresponding action.

Approach (1) - seems very inelegant to me. Playing with form action seems unnecessary. Approach (2) - would obviously not work if your javascript is turned off and is not very elegant either.

There must be a third way to doing this?, which would make me happy?

听起来您可能需要两种不同的形式才能执行两种不同的操作。

You need to get the HTML correct first.

You have two different actions, so you should have two forms - a good rule of thumb is that each form should only have one submit button. This is the best practice for HTML and will ensure that the page works without JS or any other trickery.

Once you have the page working like this, use JS to manipulate the DOM to produce the UI that you need. This is using JS to add behvour to the UI and is best practice for unobtrusive JS.

(If you really want to conflate your actions in a single form, changing the action of the form with JS is the best course of action. But consider what would happen if a user checks a check box and then changes their mind and uploads a file leaving the checkbox checked. You should take care that this shouldn't delete anything.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM