Search code examples
javascriptjquerycssinputkeyup

Simplifying some jQuery code of keyup inputs


Thing that I'm making

I am making a webpage, which is to generate forum code automatically when I enter content into inputs. Each character will be in different colors and the sentence will look like a gradient.

This is the jsfiddle sample.

When I enter a-p-p-l-e in to those inputs, the result will be as follow:

[color=3173d8]a[/color][color=416cd9]p[/color][color=5e5bdb]p[/color][color=8248dd]l[/color][color=a335df]e[/color]

Question

When more and more inputs and spans are created, the js code will be so bulky. But I don't know how to simplify them. I have tried to use thing like $(this).attr('target') , it just doesn't work. Can anyone help me to make it shorter if I would like to add more inputs, like saying 30.


More

What if i want the focus move itself to the next input if that input is typed with character already? Then I will be able to type word with 'tab'.


Solution

  • You can simplify your code like this.

    Bind the keyup event once by using the id starts with selector.

    var colors = ["3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"]
    
    $("[id^=input]").each(function (i) {
        $(this).css('background', '#' + colors[i]);
    });
    
    $("[id^=input]").keyup(function () {
        var index = $("[id^=input]").index(this);
        $("span[id^=span]").eq(index).html('[color=' + colors[index] + ']' + $(this).val() + '[/color]');
    });
    

    Note that $("[id^='input']") will return all the elements whose id starts with "input".

    Demo Fiddle

    Edit for changing the focus

    var colors = ["3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"]
    $("[id^=input]").each(function(i) {
        $(this).css('background', '#' + colors[i]);
    });
    
    $("[id^=input]").keyup(function() {
        if ($(this).val().trim().length) {
            $(this).next().focus();
        }
        var index = $(this).index();
        $("span[id^=span]").eq(index).html('[color=' + colors[index] + ']' + $(this).val() + '[/color]');
    
    });
    

    Edited Fiddle