Javascript – Clickable icon inside input field

csshtmljavascriptjquery

I have a search input field with a magnifying glass inside the box as a background image.

What i'm trying to do is make the magnifying glass clickable to submit the form.

The icon is inside the text input field on the right of the field.

If it helps, the site uses jquery and blueprint css framework.

Best Answer

Making a background-image trigger a form submit is not pretty.

A better approach is to place a regular submit button outside the input, then style things to make it look like the button is inside. That will also preserve accessibility (e.g. blind users will be able to use your website), and pressing Enter will submit your form automatically across all browsers.

See the below code, or check out this jsFiddle for a working proof-of-concept.

<style type="text/css">
.search_field {
    display: inline-block;
    border: 1px inset #ccc;
}

.search_field input {
    border: none;
    padding: 0;
}

.search_field button {
    border: none;
    background: none;
}
</style>

<div class="search_field">
    <input name="q" />
    <button type="submit"><img src="magnifying_glass.png" alt="Search" /></button>
</div>