LoginSignup
113

More than 5 years have passed since last update.

フォームのボタンでaction先を変更するときのベストプラクティス

Posted at

毎回どう実装しようか迷うので
これからは下記で統一しようと思います。
※jQueryを使用

jsは汎用的に。

javascript
$('.submit').click(function() {
  $(this).parents('form').attr('action', $(this).data('action'));
  $(this).parents('form').submit();
});

HTMLはこんな感じ。

html
<form action="regist.php" method="POST">
  <button class="submit" data-action="regist.php">登録する</button>
  <button class="submit" data-action="input.php">入力画面に戻る</button>
</form>
  • data-actionに遷移先URLを設定
  • class="submit"を付与することでjsが起動します

※formのactionはjsで書き換えられるので何でもOKかと。

ステキです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
113