Joe Scotto
Joe Scotto

Reputation: 10877

How to give a HTML "A" tag act as a submit button

I am creating a contact form that needs a submit button but I need it to be a certain look. I need to know if there is a way to assign a form action to an A tag in html so I can submit a form with the anchor tag.

Upvotes: 1

Views: 12395

Answers (4)

Liftoff
Liftoff

Reputation: 25392

You need to use Javascript to do this:

Edit:

As some users have pointed out, using inline JS is bad practice, so I will use jQuery instead.

<form id="myForm">
    <a class="submit" href="#">Submit</a>
</form>

jQuery:

$(document).ready(function(){
    $("a.submit").click(function(){
        document.getElementById("myForm").submit();
    }); 
});

Here is your updated JSFiddle

Upvotes: 3

zzzzBov
zzzzBov

Reputation: 179136

If you need your submit button to look like a link, you should still use an <input type="submit"/> element or <button type="submit"> element.

This is particularly important for users with assisted navigation, where form controls will often react differently from link elements. As you're interested in making the submit button appear as though it's a link, the task should be done with CSS.

HTML:
<form>
    ...other fields...
    <input type="submit" value="This looks like a link" class="linkish"/>
</form>
CSS:
.linkish {
    background-color: transparent;
    border: 0;
    color: blue;
    cursor: pointer;
    display: inline;
    margin: 0;
    outline: none;
    padding: 0;
    text-decoration: underline;
}

All you have to do is remove the styles that the browser's native submit button uses, and add the link styles.

demo on jsfiddle

Upvotes: 0

Ry-
Ry-

Reputation: 225014

You should use a real submit button (<button> or <input type="submit">) and style it so that it looks like a link.

If it really has to be outside of the form element for some reason, at least use the standard HTML5 attribute:

<form id="my-form">
    …
</form>
…
<input type="submit" value="Submit the form" form="my-form">

Then you can add a JavaScript-based fallback for browsers that don’t support it:

if (!('form' in document.createElement('input'))) {
    document.addEventListener('click', function (e) {
        var form = e.getAttribute('form');

        if (e.nodeName === 'input' && e.type === 'submit' && form) {
            document.getElementById(form).submit();
            e.preventDefault();
        }
    }, false);
}

Upvotes: 1

Brandon Gano
Brandon Gano

Reputation: 6710

You may be better off using <button>Your text here</button>. This will render by default in most browsers as a button, but you can override this with CSS to render as a link.

This will negate the need for JavaScript and will preserve default browser behavior for a submit button like automatically submitting the form when pressing the enter key.

Upvotes: 1

Related Questions