Search code examples
jqueryhtmlbindtrim

Can anyone help me make this script simpler?


I have a span and a input field, and when the input field is empty, i need it the span to say "Empty". When I input some text in the field, the span will automatically add the letters/numbers to the span. If the inputs value get removed, the span will say "Empty" again.

if($.trim($('#input').val()) == ''){
    $('#span').html('Empty');
}
$('#input').bind("change keyup input",function() { 
    $('#span').html($(this).val());
    if($.trim($('#input').val()) == ''){
        $('#span').html('Empty');
    }
});

I think this can be implemented in a simpler way and hopefully inside just one function. Can this be possible?


Solution

  • It is simple: set the HTML of the #span element with a function, and execute the function both during runtime, and during certain events bound to the #input field. I recommend using .on() instead of .bind():

    // Define function that sets html value
    var updateSpan = function() {
      var v = $.trim($(this).val());
      if(v === '') {
        $('#span').html('Empty');
      } else {
        $('#span').html(v);
      }
    }
    
    // Execute function at runtime
    // We use .call() so that `this` in the function refers to our input
    updateSpan.call($('#input')[0]);
    
    // Bind the function as a callback during these events, too
    // The element is automatically passed as `this`
    $('#input').on('change keyup input', updateSpan);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="input" />
    <span id="span"></span>

    If you really like confusing code, you can even shorten the if statement into this:

    var updateSpan = function() {
        var v = $.trim($(this).val());
        $('#span').html(v === '' ? 'Empty' : v);
    }