4

I'd like to create an input field for a memory game where every correct letter is (in plaintext) displayed green and every incorrect letter is displayed red inside the input field.

The word that has to be entered is available as a string, so I can compare the input with the solution.

How can I make each letter in the input field a different color based on wrong (red) or right (green)?

I found this solution for random colors but i don't really get the transfer to my case.

Community
  • 1
  • 1
Raggamuffin
  • 699
  • 1
  • 6
  • 19
  • Why on earth would you want to do that? But if that's what you want, then what have you tried so far? – AndrewL64 May 20 '16 at 21:12
  • 1
    This is for a kind of memory game... there is no sensitive data involved. the term 'password' i used to illustrate the idea. – Raggamuffin May 20 '16 at 21:17

2 Answers2

4

Unfortunately there is no easy, elegant way to achieve what you want. And by elegant I mean CSS. (there is the ::first-letter pseudo element, but no ::n-th-letter :( which could've open quite a few posibilities). Your best bet is to wrap each of your letters with a span, and then apply color to them according to a certain condition.

<span>a</span><span>b</span><span>c</span><span>d</span>

var word = 'abcd';
var matches = [0, 1, 1, 0];

$(document).ready(function() {
  for(var i = 0; i <= word.length; i++){
    $("span").eq(i).css('color', matches[i] ? 'green':'red');
  };
});

Check it out on jsfiddle.

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
3

It's just a matter of deciding which color (red/green) based on the match - here's a variation of the code from the jsfiddle you referred to:

var correctString = "abcdefg"; // for example, this should come from your code
$("div").prop("contentEditable", true).blur(function(){

  $("#hidden").val($(this).text());
  this.innerHTML = "";

  var chars = $(this).text().split("");
  chars.forEach(function(c,i){
    // pick green if characters match, red otherwise
    // any "extra" characters are automatically red
    var color = ( i < correctString.length && c === correctString.charAt(i) )? "#0F0" : "#F00";
    $("<span>").text(this).css({ color: color }).appendTo("div");
  });
});
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39