Search code examples
javascriptjqueryrefactoringconditional-execution

Javascript conditional execution and simplification


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/


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/