user3925803
user3925803

Reputation: 3295

jQuery set an elements background color based on its value

I'm going for something like this:

<script>
    $(document).ready(function(){
        $(".colored").css("background-color", "rgb(255, 100 + $(this).val(), 0)");
    });
</script>

The goal being that all elements of class "colored" will be shaded based on the value of each element. How can I get it working? Thanks.

Upvotes: 0

Views: 1571

Answers (3)

Michael Coker
Michael Coker

Reputation: 53674

You can use $.each() and $.text() to loop through them and apply the text content value as part of the background color.

$('.colored').each(function() {
  $(this).css('background-color','rgb(255,' + (100 + parseInt($(this).text()) ) + ',0)');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="colored">50</div>
<div class="colored">100</div>
<div class="colored">130</div>

Or assuming these are input tags, you would use $.val()

$('.colored').each(function() {
  $(this).css('background-color','rgb(255,' + (100 + parseInt($(this).val())) + ',0)');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="colored" value="50">
<input type="text" class="colored" value="100">
<input type="text" class="colored" value="130">

Upvotes: 2

Damith Asanka
Damith Asanka

Reputation: 964

Use this, assume your html element is div, if it is text box use $(this).val() instead of $(this).text()

 $(".colored").each(function(i){
     var shaded  = 100 + parseInt($(this).text());
      $(this).css("background-color", "rgb(255, "+shaed+", 0)");
    })

Upvotes: 0

ullfindsmit
ullfindsmit

Reputation: 300

Try the code below

<script>
    $(document).ready(function(){
        $(".colored").each(function(){
            $(this).css("background-color", $(this).val() );    //Will only work for form elements that support val() function
            // alternatively you could add a data-color="red" kind of attribute to explicitly set color for all elements 
            // $(this).css("background-color", $(this).data("color") ); 
        })        
    });
</script>

Upvotes: 0

Related Questions