2012-01-26 9 views
3

<a href="http://test/com/tag/test">Test</a>をフォームボタンのように動作させるにはどうすればよいですか?そして、フォームボタンのように振る舞い、私は、method="get"を行うためのリンクをクリックするか、投稿または投稿することでそれをキャプチャできることを意味します。タグを入力ボタンのように動作させる

リンクである必要はありませんが、私はそのように動作するように適応することができます!

答えて

5

あなたは、リンク使用してフォームを送信したい場合:

HTML -

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

JS - trigger()ため

$(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; 
    }); 
}); 

ドキュメント:http://api.jquery.com/trigger

ページを離れることなく、フォームを送信したい場合は、AJAX呼び出しを使用することができます.on()はjQueryの1.7で新しく追加され、この場合、あることhttp://api.jquery.com/jquery.ajax

注:$.ajax()ため

$(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; 
    }); 
}); 

ドキュメントを.bind()と同じです。

+0

FrankieのソリューションはAJAXを使用しています... '$ .get()'関数は'$ .ajax({type: 'get'})'です。私は '$ .ajax'コードをフォームのデータをインクルードするように更新しました。これはおそらくかなり重要です:) – Jasper

2
<form ....> 
    <a id="whatever" href="http://test/com/tag/test">Test</a> 
</form> 

あなたがIDを使用して、フォーム内の任意の要素を持っていると仮定すると、あなたはそのIDを選択して、それにclickイベントをアタッチするjQueryのを使用します。この特定のケースではgetを使用して/whatever.phpのデータを要求し、get/postの両方を使用するように調整し、必要に応じてフォームデータをシリアル化するかどうかを調整する必要があります。

$("#whatever").click(function(){ 
    $.get("/whatever.php"); 
}); 
+0

は、それが 'を'に設定することが必要でしょうか? – Alex

+0

@ w0rldart、いいえ...あなたはフォームなしでやることができます。 – Frankie

+0

フォームのデータをリクエストに含める場合は、 '$( 'form')。serialize()を' $ .get() '関数の第2引数として追加することができます:http:// api。 jquery.com/serialize – Jasper

0

とjQuery

なし
<form id="your_form"> 
    <a href="javascript:{}" onclick="document.getElementById('your_form').submit(); return false;">submit</a> 
</form> 
関連する問題