Question

I have the following script which works great however I think this can be simplify, right? also, I'd like it to trigger only once.

Example, user inputs "My Title". Script executes and user sees "my-title" in slug field. If user replaces title value by "My Crazy Title", I'd like the slug to remain "my-title". How?

$('#article_title').change(function() {
  str = $('#article_title').val();
  formatted = str.replace(/\s+/g, '-').toLowerCase();
  $('#article_slug').val(formatted);
});

See code example http://jsfiddle.net/TSrYu/

Was it helpful?

Solution

You can simplify it this way:

  1. Switch to using .one() to register your event handler so it only fires once.
  2. Remove the intermediate variables and just process the string all at once

The code:

$('#article_title').one('change', function() {
    $('#article_slug').val($(this).val().replace(/\s+/g, '-').toLowerCase());
});

Working demo: http://jsfiddle.net/jfriend00/XGjWA/

OTHER TIPS

var changed = false;
$('#article_title').change(function () {
    // do some other stuff
    if (!changed) {
        str = $(this).val();
        formatted = str.replace(/\s+/g, '-').toLowerCase();
        $('#article_slug').val(formatted);
    }
    changed = true;
});

http://jsfiddle.net/mohammadAdil/TSrYu/1/

There are two minor improvements you can make:

  • Not making your variables global by declaring them properly.
  • Not querying the DOM again for the element, since it's already available by accessing this

To make sure it only happens once, you can unbind the event (last line in snippet

$('#article_title').change(function() {
  var str = $(this).val();
  var formatted = str.replace(/\s+/g, '-').toLowerCase();
  $('#article_slug').val(formatted);
  $(this).unbind("change");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top