Search code examples
javascriptjquerychaining

jQuery chaining val()


I have a user chosen background color:

var _back = "#FF0000";  

Why doesn't this set the background color of my input field:

$("#input").val( _back ).css("background-color",$(this).val());  

when this does:

$("#input").val( _back ).css("background-color",$("#input").val());  

It does, however if I introduce a .each()

$("#input").val(_back).each(function(){$(this).css("background-color",$(this).val()) })

Solution

  • You allready have the value in a variable. just add that in the css method:

    $("#input").val( _back ).css("background-color",  _back);
    

    Another reason this would be better, is that you dont need jQuery to start the method .val(), which saves some overhead.

    The reason it doesn't work is because $(this) in the css method doesnt exist (well, it does, but its not pointing to the element you want). Functions like each or animate set the this value, css doesnt. This probably is because there are not alot of reasons to use this in css