Generate a unique slug in Javascript using the provided name and then show it in a disabled input field

Currently, I am working on a feature to generate a slug dynamically using Javascript. I want my users to be able to preview the slug before submitting the form. Below is the Javascript code I have written:

function createSlug(text) {
  return text
    .toString()                     
    .toLowerCase()                  
    .normalize('NFD')       
    .trim()                         
    .replace(/\s+/g, '-')           
    .replace(/[^\w\-]+/g, '')       
    .replace(/\-\-+/g, '-');        
}

function updateSlug(text) {
 document.getElementById("slug").value = createSlug(text); 
}

Here is the HTML structure I am using, leveraging Bootstrap 4:

<form class="form">
      <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" onkeyup="updateSlug(this)" id="name" name="name" placeholder="Example input placeholder">
  </div>
      <label for="slug">Custom 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 encountered an error stating that the function 'updateSlug' does not exist. I am using Laravel mix to compile my code. Can someone guide me on what I might be doing wrong?

Answer №1

To update the functionality, simply switch

onkeyup="listingslug(this)"
to
oninput="listingslug(this.value)"

function createSlug(text) {
  return text
    .toString() // Transform into string
    .toLowerCase() // Convert to lowercase
    .normalize('NFD') // Normalize Unicode characters
    .trim() // Remove leading and trailing whitespaces
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/[^\w\-]+/g, '') // Remove non-word characters
    .replace(/\-\-+/g, '-'); // Replace multiple hyphens with single ones
}

function updateSlug(text) {
  document.getElementById("slug").value = createSlug(text);
}
<form class="form">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" oninput="updateSlug(this.value)" id="name" name="name" placeholder="Enter name">
  </div>
  <label for="slug">Desired 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Node.js Express server does not provide access to certain static files

I am currently utilizing the angularjs-gulp-browserify-boilerplate for my development environment on Windows 10. Once I run gulp in dev mode, static files are moved to the build directory: ./build |_js |_css |_img |_fonts |_lang In additio ...

"Adding an active class to a link based on the current page and locale: A step-by-step

Looking to add an active class to the subheader menu on the active page, but facing issues when changing the locale in the link. While it works for links like my-site/my-page, it doesn't work for links like my-site/fr/my-page. Utilizing Storyblok head ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specif ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

Becoming an expert at managing and solving dependency conflicts

I am facing an issue while setting up a project from my work computer to my home computer due to fixed dependency versions. Here are the dependencies causing the problem: "dependencies": { "@nestjs-modules/mailer": "2.0.2&qu ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

A guide on transforming Jonatas Walker's TimePicker into a custom JavaScript class or a versatile jQuery plugin

I came across a timepicker solution on this Stack Overflow answer that I really liked. However, I encountered difficulties trying to implement it in a project where input elements are dynamically created. It seemed like the timepicker required specific han ...

Designating a class for the main block

Having an issue with a slider in uikit. When the slide changes, the visible elements also change their class to uk-active. I'm trying to select the central element from the active ones but css nth-child doesn't work. Any suggestions on how to do ...

Can you explain the distinction between using router.METHOD() versus router.route() in Express?

There are two different ways I've come across of writing this code. router.get(path, callback) and router.route(path).get(callback) Based on the surrounding code, they seem to have the same functionality. The documentation for these methods can be ...

Revamping repetitive JavaScript code for the pagination of Instagram Stories

I'm currently developing a website that utilizes fullpage.js and includes a section with multiple slides. These slides automatically transition every 10 seconds. I wanted to implement progress bars similar to those on Instagram, where each bar fills ...

What is the best way to trigger a re-render in a child component in React using forceUpdate

Is there a way to force reload a child component in React, similar to using this.forceUpdate() for a parent component? For example, consider the following scenario: buttonClick = () => { // This updates the parent (this) component this.forceUpda ...

What strategies can I use to eliminate nested loops while constructing a navigation?

I am working with a JSON file that contains data for a navigation panel consisting of links. A brief snippet of the file is shown below: [ { "category": "Pages", "links": [ { "url": "#", "cap ...

Is it necessary to specify the inputs property when defining an Angular @Component?

While exploring the Angular Material Button code, I came across something interesting in the @Component section - a declared inputs property. The description indicates that this is a list of class property names to data-bind as component inputs. It seems ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Leveraging AngularJS to Connect Controller Functions with Service Attributes

Just dipping my toes into the world of ngJS. I've managed to successfully bind the service objects to controllers. Is this the best way, or is there a more recommended approach? I'm also curious why this functionality seems limited to objects ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Extract items from javascript array based on their index value

Recently I came across a javascript array var countries = ["India","USA","China","Canada","China"]; My goal is to eliminate "China" only from the 2nd position while keeping the rest intact. var countries = ["India","USA","Canada","China"]; I am see ...