Make a tag act like input button

2019-07-03 00:17发布

How can I make an <a href="http://test/com/tag/test">Test</a> act like a form button? And by acting like a form button I mean that when clicking the link to do a method="get" or post in order to be able to capture it by get or post.

Not necessary has to be a link, I can adapt in order to make it work like that!

3条回答
倾城 Initia
2楼-- · 2019-07-03 00:32
<form ....>
    <a id="whatever" href="http://test/com/tag/test">Test</a>
</form>

Assuming you have any element inside your form with an ID, you use jQuery to select that ID and attach a click event on it. On this particular case it will also use a get to request data from /whatever.php and you should fine tune it to use both get/post and serialize the forms data or not according to your needs.

$("#whatever").click(function(){
  $.get("/whatever.php");
});
查看更多
叛逆
3楼-- · 2019-07-03 00:32

And without jQuery

<form id="your_form">
    <a href="javascript:{}" onclick="document.getElementById('your_form').submit(); return false;">submit</a>
</form>
查看更多
Luminary・发光体
4楼-- · 2019-07-03 00:40

If you want to submit a form using a link:

HTML --

<form action="my-page.php" id="my-form" method="post">...</form>
<a href="#" id="form-submit">SUBMIT</a>

JS --

$(function () {
    $('#form-submit').on('click', function () {

        //fire the submit event on the form
        $('#my-form').trigger('submit');

        //stop the default behavior of the link
        return false;
    });
});

Docs for trigger(): http://api.jquery.com/trigger

If you want to submit the form without leaving the page, you can use an AJAX call:

$(function () {
    $('#form-submit').on('click', function () {

        //cache the form element for use later
        var $form = $('#my-form');
        $.ajax({
            url     : $form.attr('action') || '',//set the action of the AJAX request
            type    : $form.attr('method') || 'get',//set the method of the AJAX reqeuest
            data    : $form.serialize(),
            success : function (serverResponse) {

                //you can do what you want now, the form has been submitted, and you have received the serverResponse
                alert('Form Submitted!');
            }
        });
    });

    $('#my-form').on('submit', function () {

        //stop the normal submission of the form, for instance if someone presses the enter key inside a text input
        return false;
    });
});

Docs for $.ajax(): http://api.jquery.com/jquery.ajax

Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().

查看更多
登录 后发表回答