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.
Alan Gutierrez says:
1) Doh! :^o
2) My point really was that you had to assign a function, and using the function keyword made that explicit. I didn’t slow down enough to see that it was redundant.
3) Nice post on how to use functions an eval!
Adrian Sutton says:
Alan,
Your code was actually quite good, my comments came out sounding harsher than I intended. Probably should have been “not the simplest solution” rather than “overly complicated”.
Mostly I just wanted to play around with JavaScript and it’s funky everything’s kinda sorta a string kind of philosophy. It was about time I put something code related in this blog.
Pingback/Trackback
Symphonious » More JavaScript Fun