Dynamic form submission using javascript - how to elegant code? - javascript

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?

It sounds like you may need two different forms, for the two different actions.

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.)

Related

Handling multiple HTML submit button presses from form in WordPress

So I’m running a WordPress site and it has a form I have made using HTML with a text field, an email field, a password field, and a submit button.
The problem is that users can spam the submit button, and users are occasionally prone to do that as I’m using AJAX to handle the form submission which can take a while.
Any elegant solutions would be good. I have a few suggestions I think could work but I’m not sure how to implement them, if they will actually work, or if they’re even viable.
First possibility I’m thinking of — when WordPress loads a new page, it often has the swirly loading screen with a grey background. could I have the loading screen come on prematurely, as in at the point when I run any AJAX code, too, rather than just when it changes page?
Second possibility I’m thinking of — is there a way to block all of the form fields and the submit button from being pressed as soon as you click it so it cannot be spammed and fields cannot be changed? Could this work via JavaScript (sorry not the best with JS)?
Third possibility I’m thinking of — is there a way that the system only accepts one form from an IP in the space of 5-10 seconds and any other submissions of a POST request in that cooldown time are ignored?
Would any of the above solutions work or be viable enough to work? If so, how would or could they work? I’m thinking the second one is probably the easiest to implement? However, wouldn’t the first one confirm to the user that we’re processing their data so it’d be better for the UX?
Fourth possibility that considers UX and the solution I feel is more practical — is there a way to block the submit buttons and input fields from being pressed or edited once the submit button has been pressed once, and then have a swirly loading bar appear below or above it (maybe via CSS and HTML?) so users know the site is doing something or loading?
Something just to note — the change must be client side only and the change should not affect the user if they come back to the page in future, meaning it should not remain blocked if they refresh the page or come back to it later. I know it’s implied, but wanted just to specify that.
Since you're doing this as an AJAX request, i imagine you currently have some javascript tied to the onsubmit event. Most likely this function of yours encodes the data to JSON and then sends it to the server using ajax.
One way you could accomplish this, is:
Introduce a new variable in the global scope (so outside of the onsubmit-handler); like var submission_cache = ''; or the like.
Next, inside your onsubmit handler, between the stage where you have 'encoded the entire form to a single json string' and the stage where you 'actually send the data', you compare the json to the submission_cache variable. If it matches you ignore the submission, if it doesn't match then you store a copy of the json (or a sha1 checksum of it) in submission_cache, and then just continue with the ajax stuff.
This way:
Since it is a variable on the page, the cache has the same lifetime as the page. If they leave your site and return later, the variable will be empty again, and they can submit identical info as the last time.
Secondly, if they notice they made a typo 1ms after they submitted, they can resubmit (since the cache wont match), which i imagine is desirable.
Another solution that you could use in addition to the above is to simply enable the disabled attribute on the submit button (inside your onsubmit handler function. Re-enable it after a setTimeout or in one of your ajax onreceived/onerror closures.

How to link HTML5 input to two forms

I have an input that's used by JS to control submitting two forms with different actions, but only one of them will be submitted and it should include this input.
I can do it with a hidden input using JS to change their values when the original one changes but I'd like to know if there is an HTML5 solution.
Here is my JS code to do it:
$(function(){
$('#originalOne').change(function(){
// check if I should disable a form
$('.hiddenOnes').val($(this).val());
})
});
I think I might be understanding what you are asking, correct me if I'm wrong:
"Is there a way to update the values in one form based on the values in another using HTML5 only (without using JavaScript)?"
Unfortunately, the answer there is NO. You will need to attach event listeners and handle changes using JavaScript. I had previously suggested using a <fieldset> to group the inputs that you wanted to disable independently, but this method does not work for multiple form actions.

In Salesforce open the edit screen after the object was created with Javascript button

In Salesforce, we have a button that creates events with the fields already filled out, but after the item is created I want it to reload the screen in the "Edit" view in case they want to change anything. Any ideas?
Do you need to validate fields values? Maybe it will be easier to do with field validation rules? It can be useful in cases when your data is populated not only from user screens, but also can be created in code (classes/triggers) or via API.
If you know that you exactly should to use JavaScript, you can add standard event attributes to command buttons on your Visualforce page and write JS functions for implementation of your validation logic.
I ended up creating a visualforce page with a controller and a custom button to accomplish what I needed.

defaultChecked; why this property even exist?

Taking JavaScript this semester. I cannot grasp how this property can be useful at all. This property gives a Boolean value of true IF the checked attribute was used in tag for the check box object...BUT if I am the one writing the program ...I should know if I wrote that into the program correct? I just do not see the logic in this property. Anybody have a better reason for the use of it?
First, to answer your question, "Don't I know?". Of course not. If you are thinking of a form that is only used to add records, I could see your point but forms are also used to update records and we have no idea what the initial value is for any given record that may need to be updated.
The next thing to understand is that the same concept applies to more than check boxes. For example the text input elements have a "defaultValue" property that parallels the logic of default checked property.
The next point, is these properties would be better understood by novices had they been named "initialxyz" rather than "defaultxyz". Novices think that they are used to identify what should be sent to the server if not populated by the user but that is not what they are at all. They are the initial value, as sent by the server to the client, before the user starts interacting with the screen.
To answer your larger question, these propertied are extremely useful in two cases. The first has already been mentioned which is the "reset" button or as I jokingly call it the "oops" button or "start over". That can occur at the record level that resets every element on the form but it can be used on a field by field basis where only the field that has focus is reset. For example, the escape key is often used for this purpose. The second use for this is to know if the form is "clean" (unchanged) or dirty (changed, in at least one small way somewhere). This is used in too commentary places that you did not think about. The first is to avoid submitting a form with no changes to the server. Why waste resources. The complementary is to pop up the "are you sure you want to lose your changes" when someone attempts to navigate away from a form with changes. You walk the form and compare the current valued to the initial value for each element. If no elements changed the form is clean and allow the user to leave without a prompt. If at least one element is different than it's initial value and take appropriate action which might be to prompt to confirm leaving or it might be to submit the form changes to the server before leaving or something that neither of us have thought of yet.
Hypothetically, you might have a form with lots of fields written in html, and you may want to have a "reset" button which resets all of the form fields back to their initial values. (I don't really know why that used to be a common form button, I've never seen a use for it...) The code to reset checkboxes would then be:
input.checked = input.defaultChecked;
which would be the same for all checkboxes, and then you wouldn't need to track the difference between default checked and no default checked ones separately.
Really though, it doesn't appear to have much use, and I've never used it before.
One scenario would be when you are creating checkboxes dynamically, on-the-fly, in your code. The creation may be dependent on a couple of parameters, some of them depending in turn on selections by the user, from the current screen/page.
You may wish to set what is the state of these newly created checkboxes by default, before the user performs any actions on them.
Exemplifying: Say you have a textbox where the user has to tell you how many new checkboxes you should create for whatever further actions. Then after the user enters the input, your javascript creates N checkboxes, accordingly. And their initial state is set according to "defaultChecked".
Just yesterday I found myself using this same attribute. It comes in very handy when trying to set certain values to default.
Have you ever signed up for something ad then found yourself receiving TONS of unwanted newsletters? or you install one thing and two more things start installing? This happens because there was an option somewhere with a checkbox that had the checked attribute to make that decision for you.
Mostly it is used to make decisions for the user. Comes in handy sooner than later!
BTW: Welcome to the sweet world of JavaScript!

Javascript submitting all the forms on a page

I'm using jsf 1.2. When a particular jsp has more than one form with a specified id, for example when using something like below, jsf gives the form a seemingly random id.
<ui:repeat>
<h:form id="repeatingform">
...
I would like submit all forms using javascript. Is there a way to do this without knowing the ids of the forms?
Submitting more than one form at once it not really possible. The problem is that each form requires its own separate request - submitting a form is basically similar to clicking a link, and you can't open all links on a page at once (you can by opening them in new tabs/windows, but that's a different matter)
If you really do want to keep each form its separate form element, you can use Aquatic's example,
var forms = document.getElementsByTagName("FORM");
for (var i=0; i<forms.length; i++)
forms[i].submit();
but replace the code which runs submit() with code which submits the form using XMLHttpRequest. You can have multiple XMLHttpRequests running in the background.
Hmm, It won't work like that real easy. If you would use something like document.form1.submit(); it posts that specific form and all values in it.
So it's no use looping through all the forms and submitting every single one.
That would be the same as clicking on the submit button of each single form, resulting in each form being posted separately.
The solution is to collect the values of each field in each form in a single collector form, and post the collector form.
You can read (with code examples!) more about it here: http://www.codetoad.com/forum/15_24387.asp
You can access all forms on the page in the next way
var forms = document.getElementsByTagName("FORM");
for (var i=0; i<forms.length; i++)
forms[i].submit();
I think there are several parts of this problem.
1. Are you trying to submit multiple forms in JSF? There is a way you can seggregate components in different forms and then submit a chosen group of them if req. The outer tag may be and inside these you may have as many as you may like. (Please know t:subform is a tomahawk library; but it works well with JSF). Also Subforms can be submitted in a chosed group using t:commandButton.
Notice the last paragraph on subform deocumentation that all forms with comma seperated id's may be submitted. so for example
some input controls here
more controls here
whole lotta controls here
something like this will allow you to submit selective forms and validating components only for forms you wish to validate. If that is what you are really trying to do here.
But if your intent is really to submit these forms by a single piece of java script I have a small advise, javascript supports lookup of form tags dynamically in a dom tree as shown in above example by aquatic. you could traverse those ui elements also by implementing a PhaseListener which gets invoked before "RENDER_RESPONSE" phase and there traverse the ComponentUITree to get the names or list of all the UI components and then provide them to javascript by scriplet variables or $ variables that JSP 2 supports.
I could give more detailed answers or examples if you could exactly lay out your problem, as to WHY you want a common java script and do you intend to submit multiple forms parallely or you intend to submit them one at a time ( as and when requiered) but by a common piece of java script.
Parallel submission of HTML form component is really not possible until and unless u use javascript to accumulate component values from all forms and then do whole lot of manual maipulating.
Give more details on your actual intent.

Categories

Resources