The day eventually dawned when I needed to use a form within a (ASP.NET) form. The contained form didn't need to be run at the server so I didn't envisage a problem. The form was just a simple textbox and submit button. When the form was submitted it would send the contents of the textbox to a site hosted on a different server (using the GET method).
Unfortunately, when I clicked submit, the page posted back because the server form was fired. When I hit return on the textbox the page also posted back. I needed to stop the postback and this is how I accomplished the task. There may well be easier ways of doing this, but at the end of the day it worked, so I was quite happy.
First up, I removed the form and changed the submit button to an image - that was one form control less. Next, I tested for a return/enter key press on the textbox. By testing for the carriage return, I could intercept the postback event. All I needed to do then, was to set up a couple of JavaScript functions to take care of the business.
In order to make my submit image seem to work as a submit button, I added an 'onclick' which called the following function:
function search() {
var searchTerm = document.forms[0]['txtClient'].value;
if (searchTerm != '') {
window.location = "http://www.....?st=" + searchTerm;
}
}
The first line just checks the value of the textbox - if there's nothing in it then don't jump to the external url.
Here's the textbox HTML:
<input id="txtClient" onkeypress="return checkReturn(event);" type="text" class="search-box" />
The function being called 'onkeypress' is:
function checkReturn(e) {
var evtobj=window.event? event : e;
var iKeyCode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
if (iKeyCode==13) {
search();
return false;
}
}
In this function, the key code is determined using a simple browser check. Firefox uses the event object and charCode rather then keyCode. If the Unicode value is 13 (carriage return) then call the search function. By returning false I am disabling the postback on the server form.
And that was it - a simple but effective workaround. One other thing that I did was to put a CSS class on the image (the dummy button) that would show a hand for the cursor - not that necessary but at the end of the day, I guess it was a kind of hyperlink after all.