javascript - HTML5 input type color doesn't show value when created via js - Stack Overflow

I am creating a table via javascript and one column will contain an html color picker. The problem that

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?

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?

Share Improve this question asked Oct 10, 2013 at 7:06 stephan2307stephan2307 3571 gold badge4 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745443345a4627930.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信