Skip to content

Instantly share code, notes, and snippets.

@simonw
Created May 8, 2021 15:04
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 simonw/ce890736d333fee55268d528a1141136 to your computer and use it in GitHub Desktop.
Save simonw/ce890736d333fee55268d528a1141136 to your computer and use it in GitHub Desktop.
Pre-fill the slug form field based on the title, but stop doing that if the slug is manually edited
function slugify(s) {
return s
.toLowerCase()
.replace(/[^-\w\s]/g, "") // remove non-alphanumerics
.trim()
.replace(/[-\s]+/g, "-") // spaces to hyphens
.replace(/-+$/g, ""); // trim trailing hyphens
}
function slugAutoFill() {
var titleInput = document.querySelector('#id__save-title');
var slugInput = document.querySelector('#id__save-slug');
if (!titleInput) {
return;
}
let slugManuallyEdited = false;
slugInput.addEventListener('change', () => {
slugManuallyEdited = !!slugInput.value;
});
function titleEdited() {
if (slugManuallyEdited) {
return;
}
slugInput.value = slugify(titleInput.value);
}
titleInput.addEventListener('change', titleEdited);
titleInput.addEventListener('focus', titleEdited);
titleInput.addEventListener('keyup', titleEdited);
}
slugAutoFill();
<p><label>Title <input type="text" id="id__save-title"></label>
<p><label>Slug <input type="text" id="id__save-slug"></label>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment