Websites/app/javascript/ujs-prompt.ts
2024-05-02 22:04:43 -05:00

32 lines
1.1 KiB
TypeScript

/// <reference lib="dom" />
import $ from "jquery";
function ujsPrompt(el: HTMLElement) {
const link = $(el);
const href = link.attr("href"),
method = link.data("method"),
csrfToken = $("meta[name=csrf-token]").attr("content"),
csrfParam = $("meta[name=csrf-param]").attr("content"),
form = $(`<form method="post" action="${href}"></form>`),
msg = link.data("prompt"),
value = prompt(msg),
paramName = link.data("param-name") || "prompt-value",
promptParamInput = `<input name="${paramName}" value="${value}" type="hidden" />`;
let metadataInput = `<input name="_method" value="${method}" type="hidden" />`
if (csrfParam !== undefined && csrfToken !== undefined) {
metadataInput += `<input name="${csrfParam}" value="${csrfToken}" type="hidden" />`;
}
form.hide().append(metadataInput).append(promptParamInput).appendTo("body");
form.submit();
}
$("a[data-prompt]").on("click", function(e) {
e.stopImmediatePropagation();
e.preventDefault();
ujsPrompt(this);
});