Joseph
Joseph

Reputation: 1744

jQuery submit form via submit button

Is it possible to submit a form by clicking a div-element as if it was submitted by the submit button?

So that this PHP works:

if(isset($_POST["share"])) { /* do something*/ }

Form:

<form id="form" action="publish.php" method="POST">

  <textarea name="description" maxlength="500">Description...</textarea>

  <input type="submit" name="share" value="Share" />

</form>

This does NOT post the share value, $_POST['share'].

if($(".post-form").length){

        $(".post-form").click(function(event) {

            $("#form").submit();
            return false;

        });

    }

Upvotes: 0

Views: 93

Answers (2)

Paradoxis
Paradoxis

Reputation: 4708

Yes this is possible by using the .submit() function. You can use it like so:

// Wait until the document has been fully loaded
$(document).ready(function() {

    // Bind a click event to your element
    $('div').click(function(event) {

        // Submit the form
        // The callback should add a hidden field with the name "share"
        $('form').submit(function(eventObj) {
            $('<input />').attr('type', 'hidden')
                .attr('name', "share")
                .attr('value', "Share")
                .appendTo('form');
            return true;
        });
    });
});

You can find more information here

Demo: jsfiddle

Upvotes: 1

Jafar Akhondali
Jafar Akhondali

Reputation: 1537

Set an id for submit button:

  <input type="submit" name="share" value="Share" id="btn_submit" />

then you can control it in jquery like this:

$("#btn_submit").onclick(function(){
    if(condition==true)
    {
        return true;
    }
    else
    {
        return false;
    }
});

Upvotes: 0

Related Questions