Simplifying some jQuery code of keyup inputs

246 views Asked by At

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'.

2

There are 2 answers

10
Anoop Joshi P On BEST ANSWER

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

0
user2226755 On

Automatic making input, and full js solution. And it's easy to add new color.

// Define color separately
var colors = [
  "3173d8", "416cd9", "5e5bdb", "8248dd", "a335df"
];

(function() {
  $("body")
    .append('<div id="parent"></div>')
    .append('<code id="output"></code>');

  var f = function() {
    $("#output").html("");

    for (var i = 0, val = ""; i < colors.length; i++) {
      val = $("#parent input[data-num=" + i + "]").val();
      $("#output").append('[color=' + colors[i] + ']' + val + '[/color]');
      //or $("#output").append('<span id="span'+i+'">'+c+'</span>');
    }
  };

  for (var i = 0; i < colors.length; i++) {
    $('<input size="4" maxlength="1" />')
      .attr("data-num", i)
      .css('background', '#' + colors[i])
      .keyup(f)
      .appendTo("#parent");
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>