Javascript Disabling and Timing
I need to update an application so that when a user clicks on a button, etc all of the input fields become disabled. Here is what I have so far for the javascript. The following works and everything, so no worries there.
function disableAllInputs() {
var inputs = getAllInputs();
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
}
function enableAllInputs() {
var inputs = getAllInputs();
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
function getAllInputs() {
var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
var allInputs = new Array();
var counter = 0;
for (i = 0; i < inputs.length ; i++) {
allInputs[counter] = inputs[i];
counter++;
}
for (i = 0; i < selects.length; i++) {
allInputs[counter] = selects[i];
counter++;
}
return allInputs;
}
Now, in my HTML I basically have this:
<form name="MyFo开发者_JAVA百科rm" method="post" action="MyAction.do" onsubmit="onSubmit();">
//form code
<input type="submit" value="Save" name="submit" onclick="onSaveClick()" >
</form>
Everything appears to work fine. However, I need to make it all testable. I'd like to put in a delay so that everything freezes and the tester can make sure everything is disabled, etc. But this pausing should be temporary and immediately removable without any possible side effects (i.e. it would be nice to call a pause() function and then just delete the call).
Here are some issues:
1 - If I call the disableAllInputs method in the onSaveClick method, the form does not submit (I assume because the button was disabled).
2 - If I call the disableAllInputs method in the onSubmit method, the pausing does not appear to work.
Can anyone think of an way to seamlessly pause the form submission after the buttons are disabled? I am aware of setTimeout, etc. I just can't find an appropriate call location, etc to use. Nothing seems to pause the form AND eventually submit the form.
Also, I'd have the JS in a separate .js file, so it would be nice if I could just include the file and add the disableAllInputs method where appropriate (that is, I'd like to avoid doing a timeout on the onSubmit method, etc).
Well, you can insert a pause using various methods, but all of those methods will cause the entire page to become unresponsive during the pause. The simplest example of this would be an alert box. (You could also use SJAX - Synchronous AJAX.)
You could stop the code by triggering a fatal error, such as calling a function that doesn't exist. stopJavascript();
But that wouldn't allow the code to continue anymore.
The only other option would be to split the function up into two functions and use a setTimeout
to delay the calling of the second function after the first. However, this would be harder to implement and harder to remove.
精彩评论