Skip to content

Instantly share code, notes, and snippets.

@RYLSnmm
Created September 30, 2023 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RYLSnmm/989933e7aeeba9139d8d6b44866a3286 to your computer and use it in GitHub Desktop.
Save RYLSnmm/989933e7aeeba9139d8d6b44866a3286 to your computer and use it in GitHub Desktop.
form の名前が未入力のときに自動でつける
export default ({
auto_names_promise,
local_names,
disable_local_name_suffix,
form_name,
storage_key,
}) => {
let auto_names = []
auto_names_promise.then(data => {
auto_names = data
})
return (form_data) => {
let name = form_data.get(form_name)
if (name === "") {
if (storage_key && localStorage[storage_key]) {
name = localStorage[storage_key]
} else {
if (auto_names.length) {
name = random(auto_names)
} else {
name = random(local_names)
if (!disable_local_name_suffix) {
name += String(random(1000)).padStart(3, "0")
}
}
}
}
form_data.set(form_name, name)
if (storage_key) {
localStorage[storage_key] = name
}
}
}
const random = (arr_or_num) => {
const _random = (end) => Math.floor(Math.random() * end)
if (typeof arr_or_num === "number") {
return _random(arr_or_num)
} else {
const index = _random(arr_or_num.length)
return arr_or_num[index]
}
}
<!doctype html>
<style>
.container {
margin: 10px;
width: 400px;
}
.comment-form {
:is(h1) {
font-size: 1.2em;
}
:is(textarea) {
resize: vertical;
min-height: 3em;
}
}
.flex-col {
display: flex;
flex-flow: column;
gap: 8px;
}
</style>
<div class="container">
<section class="comment-form">
<form id="comment-form">
<div class="flex-col">
<h1>コメント</h1>
<input name="name" placeholder="なまえ">
<textarea name="body"></textarea>
<button>投稿</button>
</div>
</form>
</section>
</div>
<script type="module">
import autoname from "./autoname.js"
const set = autoname({
auto_names_promise: fetch("https://example.com").then(response => response.json()).then(data => data.names),
local_names: ["さとう", "たなか", "すずき"],
disable_local_name_suffix: false,
form_name: "name",
storage_key: "last_name",
})
document.getElementById("comment-form").onformdata = (event) => { set(event.formData) }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment