Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 727
stephan2307 Avatar asked Oct 10 '13 07:10

stephan2307


People also ask

How do you set the value of an input type color?

The <input type="color"> defines a color picker. The default value is #000000 (black). The value must be in seven-character hexadecimal notation. Tip: Always add the <label> tag for best accessibility practices!

Can I make the HTML color input only display hex?

You can't make it only display hex, but whatever mode the user chooses the value is stored as hex.

How do I display color palette in HTML?

To add a color picker in an HTML page, use an <input> tag with type = 'color' . The initial value can be set using the value property. This value needs to be set in hexadecimal because colors are represented as six-digit hexadecimal values following a hashtag ( # ).

Which html5 input element will allow user to select the color from the dialog box?

<input type="color"> <input> elements of type color provide a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format.


1 Answers

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

like image 164
T.J. Crowder Avatar answered Sep 19 '22 02:09

T.J. Crowder