Forms and Non-form Elements

Let's suppose that we want to be able to submit a form (or provide other form processing) from an element inside of the form that is not considered to be actually a part of the form itself. For example if we want to use text or an image to submit the form rather than a button.

In this case the only connection that we actually have between the element that is to trigger the processing and the form we want it to process is that the triggering element is nested somewhere inside of the <form> element.

As the triggering element is not an actual part of the form, clicking on it will not trigger a submit event on the form. This means that we will need to do our processing based on the click event being triggered instead. To do this we can add a simple click event listener to that element just as we would add any event listener. That then just leaves us with how to have that event listener process the form that the triggering element is nested in.

To do this we add an extra function in between the event trigger and what we actually want to run. Let's say that we put all of our form processing code inside of a function called processForm() and that the function expects to receive one parameter which is a pointer to the form tag of the form that will therefore allow us to process all of the fields within the form. We then have our event listener call a findForm function that will find the form for us and then call our processForm function if it finds aform to process.

The code for this findForm function will always be the same code. It simply starts searching for a form tag as a parent, grandparent, greatgrandparent etc of the element that triggered the event. Either it finds a form tag and therefore runs processForm on that tag or it reaches the outermost node of the document without finding a form in which case it does nothing.

function findForm(e) {
var node = this;
while (node.parentNode && 3 !== node.nodeType && 'FORM' !== node.nodeName) node = node.parentNode;
if (node.nodeName === 'FORM') processForm(node);
function processForm(form) {


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow