Question

I have the following form for user input of three values which I then convert into hexadecimals (the function to do the conversion I am not posting, because it is not part of the problem - if you want to see it anyways, let me know.)

<form name="color">
  Red: <input type="number" name="d"> <br>
  Green: <input type="text" name="e"> <br>
  Blue: <input type="text" name="f"> <br>
  <input type="button" value="Paint" onclick="javascript:drawmycolor();">
</form>

Then I would like to set the background color of the third row of the following table in the color generated through the user input. For this I have written the following function:

 function drawmycolor()
 {
 a = Number(document.color.d.value);
 b = Number(document.color.e.value);
 c = Number(document.color.f.value);

 if (a >= 0 && a < 255 && Math.floor(a) == a &&
     b >= 0 && b < 255 && Math.floor(b) == b &&
     c >= 0 && c < 255 && Math.floor(c) == c)
 {
   mycolor = "#" + getHexadecimalValue(a) +
    ""  + getHexadecimalValue(b) +
    ""  + getHexadecimalValue(c); 

   document.write('<br><table border="1" cellspacing="1"cellpadding="1">');
   document.write('<tr><th>Hexadecimal Red</th><th>' +
   'Hexadecimal Green</th><th>' +
   'Hexadecimal Blue</th><th>' +
   'Color</th></tr>');
   document.write('<tr><td>' + getHexadecimalValue(a) + '</td><td>' + 
   getHexadecimalValue(b) + '</td><td>' + 
   getHexadecimalValue(c) +                            
   '</td><td bgcolor="mycolor"</td></tr>'); //RIGHT HERE I WANT TO SET THE COLOR
   document.write('</table>');
 }
 else
 ..

I know that everything in the function works: It puts the string "mycolor" together the right way and also prints the table like I want it. If also shows the background color of the last row if I put in a normal value like "#F0F8FF". The only thing that is not working now is to connect the background color to "mycolor" generated through the user input...

I am grateful for any help! Thank you, Eva

Was it helpful?

Solution

You should close the <td> properly

<td bgcolor="mycolor"></td>

instead of

<td bgcolor="mycolor"</td>

then, you can set the background color of the <td> programmtically like this

document.querySelector('[bgcolor="mycolor"]').style.backgroundColor = mycolor;

example -> http://jsfiddle.net/wvQJB/

or directly in the code you are writing to the page :

...
getHexadecimalValue(c) +                            
'</td><td style="background-color: '+mycolor+';"></td></tr>'); 
document.write('</table>');

Notice that bgcolor is deprecated!! See -> https://developer.mozilla.org/en-US/docs/Fixing_common_validation_problems#The.C2.A0bgcolor_attribute_is_deprecated

OTHER TIPS

Missing ">" just after <td bgcolor="mycolor"

Depending on the doc-type used, bgcolor attribute may no longer be supported.

Try "<td style='background-color:" + mycolor + "'></td>"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top