JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<label for="title">Title:</label> 
<input name="title" id="title" value="" /><br /> 
<label for="slug">Slug:</label> 
<input name="slug" id="slug" value="" class="slug" />

JavaScript

//
//    jQuery Slug Generation Plugin by Perry Trinier (perrytrinier@gmail.com)
//  Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html

jQuery.fn.slug = function(options) {
    var settings = {
        slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready() 
        hide: true     // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span. 
    };
    
    // merge options and settings
    if(options) {
        jQuery.extend(settings, options);
    }
    
    // save jQuery object for later use in callback
    if (this.length > 0) {
        var self$ = this.eq(0);
    
        jQuery(document).ready( function() {
            if (settings.hide) {
                jQuery('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
                jQuery('input.' + settings.slug).hide();
            }
            self$.keyup(function() {
                var slugcontent = jQuery(this).val();
                var slugcontent_fixed = slugcontent.replace(/\s/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
                jQuery('input.' + settings.slug).val(slugcontent_fixed);
                jQuery('span.' + settings.slug).text(slugcontent_fixed);
            });
        });
    }
    
    // return our jQuery object so it's chainable
    return this;
};

// this first call to .slug() produces an empty selector and
// does not cause errors
$("#titleXXX").slug({
      slug:'slug',
      hide: false
    });

// this second call works
$("#title").slug({
      slug:'slug',
      hide: false
    });