PEF
PEF

Reputation: 973

jQuery: Assign background colors to elements

I'm very new to jQuery, and I'd like to set the background color of elements according to their value at page load.

Each of the elements have an id ending with "*_hex" that's why I use the selector $("[id$=_hex]"), and each have a value that is a hex color.

Here is an exemple element:

<input id="product_colors_attributes_382873_hex" type="text" value="#c22424">

And here's the code I've come up with so far:

$(document).ready(function(){
$("[id$=_hex]").each(function(){
        $(this).css('backgroundColor', $(this).value);
    });
});

It works if I hardcode the color, but obviously $(this).value doesn't work. Any clues? Thanks in advance.

Upvotes: 0

Views: 79

Answers (4)

To access the value field with jquery you should use the function val()

$(document).ready(function(){
$("[id$=_hex]").each(function(){
        $(this).css('backgroundColor', $(this).val());
    });
});

Upvotes: 1

YogeshWaran
YogeshWaran

Reputation: 2281

use val() instead of $(this).value

 $(this).val() 

Upvotes: 3

Rango
Rango

Reputation: 3907

$(this).css('backgroundColor', $(this).val());

Upvotes: 2

Kevin B
Kevin B

Reputation: 95062

You should be able to use this.value, no need for jQuery to get value of an input.

Upvotes: 3

Related Questions