Recipe3.6.Submitting a Form from an Image


Recipe 3.6. Submitting a Form from an Image

Problem

You want the user to be able to submit a form by clicking an image that isn't contained within the HTML form tags.

Solution

Use a link with a JavaScript URL to submit the form:

<html:link href="javascript:document.MyForm.submit(  )">     <html:img page="/submit-form.gif"                 alt="Submit" border="0"/>  </html:link>

Discussion

Web sites frequently use clickable images instead of HTML submit buttons to trigger form submission. The Struts html:image tag can be used to generate an HTML input type="image" tag that creates such an image. However, with complex HTML layouts, it is not always possible to nest the image within the <form> . . . </form> tags. In some cases, an HTML page may have multiple forms in one section of a page, with the images for submitting the forms in a separate region of the page.

The Solution above can be used to submit a form from an image located outside of the form tags. The image to display is nested in an html:link tag. The link submits the form by executing a line of JavaScript. In the Solution, the JavaScript will submit the form named MyForm. The form name must match the name attribute from the corresponding action element in the struts-config.xml. Here is the HTML that gets generated using the Solution:

<a href="javascript:document.MyForm.submit(  )">     <img src="/books/3/113/1/html/2//myApp/struts-power.gif"          border="0" alt="Submit"> </a>

Though you could directly use the above HTML markup instead of the Struts html tags, you would lose the features provided by those tags. By using the Struts tags, you don't have to specify the context name, and you have the ability for the image name and alternate text to be retrieved from a resource bundle (if needed).

Another alternative is to use the onclick attribute of the html:img tag:

<html:img page="/submit-form.gif"        onclick="document.MyForm.submit( );"            alt="Submit" border="0"/>

The disadvantage of this approach is that most browsers won't provide a visual clue that the image is clickable. Since the image is nested in a link, most browsers change the mouse pointer to indicate that the image can be clicked as shown in the Solution.

If you want to ensure that your web application will function for clients that have disabled JavaScript, a conventional submit button should be provided somewhere on the form.


See Also

Recipe 3.9 describes how to submit a form to an alternate URL from the one specified in the form's action attribute.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net