Reputation: 23
Hopefully someone can help me here, I am writing some code to apply different colors to a text area using 3 input boxes which represent RGB, but I cant quite seem to get the values to apply. This is the code I'm playing with.
function rgb(r, g, b) {
return "rgb("+r+","+g+","+b+")";
}
document.getElementById("id1").style.backgroundColor = rgb;
<table>
<tbody>
<tr>
<td colspan="5">
<textarea id="id1" cols="50" rows="10"></textarea>
<!-- RGB value boxes !-->
</td>
<td>
R
<input type=text size=3 maxlength=3 name="r" value="0" onBlur="rgb(this.value);">
</td>
<td>
G
<input type=text size=3 maxlength=3 name="g" value="0" onBlur="rgb(this.value);">
</td>
<td>
B
<input type=text size=3 maxlength=3 name="b" value="0" onBlur="rgb(this.value);">
</td>
Any help would be greatly appreciated.
Upvotes: 2
Views: 1388
Reputation: 3356
Try this:
var r=0;
var g=0;
var b=0;
function rgb(elem) {
var name = elem.name;
var val = elem.value;
window[name] = val;
document.getElementById("id1").style.backgroundColor = 'rgb('+r+','+g+','+b+')';
}
<table>
<tbody>
<tr>
<td colspan="5">
<textarea id="id1" cols="50" rows="10"></textarea>
<!-- RGB value boxes !-->
</td>
<td>
R
<input type=text size=3 maxlength=3 name="r" value="0" onBlur="rgb(this);">
</td>
<td>
G
<input type=text size=3 maxlength=3 name="g" value="0" onBlur="rgb(this);">
</td>
<td>
B
<input type=text size=3 maxlength=3 name="b" value="0" onBlur="rgb(this);">
</td>
Upvotes: 0
Reputation: 130
I think this is essentially what you attempt to do:
function rgb() {
document.getElementById("id1").style.backgroundColor =
"rgb("+document.getElementById("red").value+","
+document.getElementById("green").value+","
+document.getElementById("blue").value+")";
}
<table>
<tbody>
<tr>
<td colspan="5">
<textarea id="id1" cols="50" rows="10"></textarea>
<!-- RGB value boxes !-->
</td>
<td>
R
<input id="red" type=text size=3 maxlength=3 name="r" value="0" onBlur="rgb()">
</td>
<td>
G
<input id="green" type=text size=3 maxlength=3 name="g" value="0" onBlur="rgb()">
</td>
<td>
B
<input id="blue" type=text size=3 maxlength=3 name="b" value="0" onBlur="rgb()">
</td>
</tr>
</tbody>
</table>
This is the working JSFiddle: https://jsfiddle.net/n74dxarn/
The reason it wasn't working for you, is because you were calling the rgb function without any parameters in the end of your javascript code, and when onBlur was activated you were calling the function with only one parameter.
I hope that helps
Upvotes: 2
Reputation: 4039
You're doing rgb(this.value)
, wich only gives the function 1 value to work with. Remove the arguments from the function, and get the rgb values inside it on the fly.
Upvotes: 0