bbrooke
bbrooke

Reputation: 2347

Using jQuery to submit form from link outside of form

I'm trying to submit a form from a link that is located in my nav bar.

I'm new to javascript.jQuery and unsure why this won't execute.

I have a feeling there I need to put something else in the link's href but I'm not sure what it is? I appreciate the feedback and expertise.

LINK

<li><a href="#" id="add-product-save-link"><i class="icon-plus"></i> Save</a></li>

FORM

<form class="form" action="" method="post" id="add-product-form">

JAVASCRIPT (this code in an external separate file I have linked to the template)

$(document).ready(function() { 
    $('#add-product-save-link').click(function(e) {
        e.preventDefault();
        $('#add-product-form').submit();
    });
});

I've linked to jQuery with:

Upvotes: 5

Views: 44278

Answers (4)

Ralph Alex
Ralph Alex

Reputation: 89

$("#button").click(function(e){

        $.post('url.php', $("#form").serialize(), function(data){

Upvotes: 1

ImmortalPC
ImmortalPC

Reputation: 1690

in pure JavaScript: (http://jsfiddle.net/4enf7/)

<a href="javascript:document.getElementById('add-product-form').submit();">Send form</a>

Upvotes: 16

Roger Barreto
Roger Barreto

Reputation: 2284

You are clicking in the "A", not in the Italic (With ID). Supposing you will not change the HTML to that work out you should use this:

$(document).ready(function() {  
    $('#add-product-save-link').parent().click(function(e) {
        $('#add-product-form').submit();
        return false;
    });
});

Upvotes: 3

cssyphus
cssyphus

Reputation: 40038

Link:

<a href="#" id="add-product-save-link" class="icon-plus" ><i>Save</i></a>

jQuery:

$(document).ready(function() { 
    $('#add-product-save-link').click(function() {
        $('#add-product-form').submit();
    });
});

You don't need the e.preventDefault(), because your anchor tag isn't going anywhere (the href is #).

Because your <form> tag's action attribute is blank, that means that the form will submit itself to this same document. If that is what you want to do, then you can put the logic for that at the top of your document:

<?php
    if (isset($_POST)) {
        //do your form processing here
    }else{
        //your normal page is here.
    }
?>

Finally, because this answer uses jQuery, ensure that you reference the jQuery library somewhere, such as in the <head> tags:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>

Upvotes: 8

Related Questions