So I have been trying to create a slug using Javascript, and allow my users to see what the slug will be, before even pressing submit. Here is my Javascript code:
function slugify(text) {
return text
.toString() // Cast to string
.toLowerCase() // Convert the string to lowercase letters
.normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
.trim() // Remove whitespace from both sides of a string
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
function listingslug(text) {
document.getElementById("slug").value = slugify(text);
}
Here is my html that I am using, which is using Bootstrap 4:
<form class="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" onkeyup="listingslug(this)" id="name" name="name" placeholder="Example input placeholder">
</div>
<label for="slug">Your vanity URL</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon3">{{ env('APP_URL') }}/listing/</span>
</div>
<input type="text" class="form-control" id="slug" name="slug" aria-describedby="basic-addon3">
</div>
</form>
I'm getting an error that listingslug does not exist. I'm using Laravel mix to compile my code. What am I doing wrong?
You just need to change onkeyup="listingslug(this)"
to oninput="listingslug(this.value)"
function slugify(text) {
return text
.toString() // Cast to string
.toLowerCase() // Convert the string to lowercase letters
.normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
.trim() // Remove whitespace from both sides of a string
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
function listingslug(text) {
document.getElementById("slug").value = slugify(text);
}
<form class="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" oninput="listingslug(this.value)" id="name" name="name" placeholder="Example input placeholder">
</div>
<label for="slug">Your vanity URL</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon3">{{ env('APP_URL') }}/listing/</span>
</div>
<input type="text" class="form-control" id="slug" name="slug" aria-describedby="basic-addon3">
</div>
</form>