The accepted answer is a reasonable work-around, but doesn’t solve your problem statement.
The problem in the line
$("#input").val( _back ).css("background-color",$(this).val());
is that $(this)
is evaluated before css()
is called.—And that is what always happens before you call a function: all it’s arguments will be evaluated beforehand. That $(this)
is evaluated on the same level with the same context as $("#input")
and both don’t know about each other.
On this line
$("#input").val(_back).each(function(){$(this).css("background-color",$(this).val()) })
both $(this)
are part of the source code of the anonymous function you create and pass to each()
. And each()
calls this function itself, so it has the opportunity to set up this
.
The “good” news is: css()
eats functions, too. The API allows both:
.css( propertyName, value )
.css( propertyName, function )
If you feed it a function, css()
will call that function, similar to each()
, but only once, and use its return value.
You can fix your line with:
$("#input").val(_back).css("background-color", function(){return $(this).val();});
Note: you can not use the arrow function () => $(this).val()
here. This is the most important difference between arrow and “normal” functions: there is no way to give arrow functions any this
. They always take it from their lexical surrounding and this would introduce the problem we are trying to solve here...