admin管理员组文章数量:1317906
How can I make an <a href="http://test//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!
How can I make an <a href="http://test//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!
Share Improve this question asked Jan 26, 2012 at 19:41 AlexAlex 7,68825 gold badges86 silver badges153 bronze badges3 Answers
Reset to default 6If 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./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./jquery.ajax
Note that .on()
is new in jQuery 1.7 and in this case is the same as using .bind()
.
<form ....>
<a id="whatever" href="http://test//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");
});
And without jQuery
<form id="your_form">
<a href="javascript:{}" onclick="document.getElementById('your_form').submit(); return false;">submit</a>
</form>
本文标签: javascriptMake a tag act like input buttonStack Overflow
版权声明:本文标题:javascript - Make a tag act like input button - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742030349a2416327.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论