stephan2307
stephan2307

Reputation: 357

HTML5 input type color doesn't show value when created via js

I am creating a table via javascript and one column will contain an html color picker. The problem that I have is that in Chrome the default value is set but the color that is displayed on the color picker is black.

This is the javascript that I am using

c = r.insertCell(1);
c.setAttribute('class','second');
inp=document.createElement("input"); 
inp.setAttribute('type','color');
inp.setAttribute('id','colo_'+i);
inp.setAttribute('value','#ffffff');
inp.setAttribute('class','datafield');
inp.addEventListener('change', saveFields);
c.appendChild(inp);

This is the html that is generated from if

<td class="second">
<input type="color" id="colo_0" value="#8080ff" class="datafield">
</td>

Is this a bug or am I doing something wrong?

Upvotes: 5

Views: 3125

Answers (2)

ItayB
ItayB

Reputation: 11337

It might be helpful for someone someday, so I'll just put it here: The value of input color seems to work only with hex value (rather than RGB) - so if your color is in RGB - switch it to hex first. RGB to hex

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074305

Interesting. I was able to replicate your results (example).

Rather than using setAttribute, set the value directly:

inp.value = '#ffffff';

Apparently that makes Chrome happy. (Live Copy | Source)


Side note: All of the things you're setting via setAttribute have reflected properties you can use instead:

inp = document.createElement("input"); 
inp.type = 'color';
inp.id = 'colo_'+i;
inp.value = '#ffffff';
inp.className = 'datafield';

Note that the last one is className rather than class.

Updated Example | Source

Upvotes: 4

Related Questions