JavaScript Fun
By Adrian Sutton
Nick Chalko talks about setting onsubmit dynamically. The solution he received from Alan Gutierrez which is good, but overly complicated. Since I work for a company that just so happens to do some amazingly funky stuff with JavaScript, here’s some fun you can have with it. Firstly, lets take the original solution:
<form name='CDiceComponent_0' id='findApplication'
action='/cdiceWebApp/custom/component/bridge.jsp' method='post'>
<script>
document.findApplication.onsubmit = function() {return checkForm();}
</script>
and simplify it to:
<form name='CDiceComponent_0' id='findApplication'
action='/cdiceWebApp/custom/component/bridge.jsp' method='post'>
<script>
 document.findApplication.onsubmit = checkForm;
</script>
JavaScript functions are just string variables so you can pass them around by just dropping the () at the end. Here’s how you could store the existing onsubmit function:
var oldOnSubmit;
oldOnSubmit = document.findApplication.onsubmit;
Then you can execute it later with:
oldOnSubmit();
Cool huh? Why stop there? Lets say the old handler contained a call to form.submit() that you wanted to remove. You could do it with:
oldOnSubmit = eval(String(oldOnSubmit).replace(/form\.submit\(\)/gi, ""));
Then execute oldOnSubmit like before, or set it back as the current form onsubmit handler. Note the use of String() to convert the function to a string and the use of eval() to convert it back to a function. Here’s an example of this coming together (probably without the typos and omissions in the above snippets).
<script language="JavaScript">
function change() {
var oldOnClick;
oldOnClick = document.findApplication.doStuff.onclick;
oldOnClick = String(oldOnClick);
var newOnClick;
newOnClick = oldOnClick.replace(/form\.submit\(\)/gi,
"alert('Submitting the form.');");
document.findApplication.doStuff.onclick = eval(newOnClick);
}
</script>
<form name="findApplication" id="findApplication">
<input type="button" name="doStuff" id="doStuff" value="Submit"
onclick="form.submit();"/>
<input type="button" name="preventSubmit" value="Prevent Submit"
onclick="change();"/>
</form>
Note: This entry has been reformatted as a previous blog migration seems to have messed it up.