Created
September 30, 2023 08:00
-
-
Save RYLSnmm/989933e7aeeba9139d8d6b44866a3286 to your computer and use it in GitHub Desktop.
form の名前が未入力のときに自動でつける
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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