Skip to content

Instantly share code, notes, and snippets.

@ucan-lab
Last active December 27, 2019 03:20
Show Gist options
  • Select an option

  • Save ucan-lab/7f6dd309f349cde82f232da8ccd0c828 to your computer and use it in GitHub Desktop.

Select an option

Save ucan-lab/7f6dd309f349cde82f232da8ccd0c828 to your computer and use it in GitHub Desktop.
jQuery フォームボタンに応じて遷移先を変更する。 ref: https://qiita.com/ucan-lab/items/09d3fe885778642d9456
<form>
<button type="submit" class="change-action" data-action="/" data-method="GET">一覧へ</button>
<a href="javascript:void(0)" class="change-action" data-action="/update/1" data-method="PUT">更新</a>
<button type="submit" class="change-action" data-action="/images" data-method="POST" data-enctype="multipart/form-data">ファイルアップロード</button>
<button type="submit" class="change-action" data-action="/images/1" data-method="DELETE">画像削除</button>
</form>
"use strict";
$(function () {
/**
* ボタンのdata属性からフォーム属性を変更
*/
$(".change-action").on("click", function (event) {
// デフォルトアクションを抑止
event.preventDefault();
let form = $(this).parents("form");
// action
if ($(this).data("action")) {
form.attr("action", $(this).data("action"));
}
// method
if ($(this).data("method")) {
if ($.inArray($(this).data("method"), ["GET", "POST"]) == -1) {
// PUT, DELETE
var element = $("<input />", { type: "hidden", name: "_method", value: $(this).data("method") });
form.append(element);
form.attr("method", "POST");
} else {
// GET, POST
form.attr("method", $(this).data("method"));
}
}
// enctype
if ($(this).data("enctype")) {
form.attr("enctype", $(this).data("enctype"));
}
// debug用
console.log(form.attr("action"));
console.log(form.attr("method"));
console.log($("[name=_method]").val());
console.log(form.attr("enctype"));
// submit
form.submit();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment