Reputation: 3295
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
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
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
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