Only sometimes we want to be able to be able to see and edit the hex code directly rather than only using the O/S user interface.
If you're not familiar with current browser behaviour, what our script is adding is this text field alongside the color input element:
The two fields are linked so that changing either one will update the other. When the form is submitted, however, the new field will be ignored because it has no name or id attribute.
You'll see that we've added a pattern to the text input field which will trigger HTML5 Form Validation.
HTML FORM markup
As stated earlier, all you need for this to work is an HTML5 colour input somewhere on the page. Here is the skeleton HTML markup for the above form:
<form method="POST" action="#"> <p>Colour Name: <input type="text" size="32" name="name" value="Aluminium"><br> Colour: <input type="color" size="32" name="color" value="#b5b5b5"><br> <input type="submit" value="Save Changes"></p> </form>
Note that the color input field defaults to #000000 (Black) rather than blank/null. If you want to allow blank values to be submitted or recorded you will need to work around that.
The script that does this can be applied on page load. It scans the entire page for any color input fields and attaches a text field to any found:
This code can be included anywhere on the page or in an external file. It will run only once, when the page has finished loading.
Please feel free to use and adapt this code for your purposes, and you can contact us with any comments or questions using the button below.
Related Articles - Form Validation
- HTML5 Form Validation Examples [HTML]
- Validating a checkbox with HTML5 [HTML]
- Protecting forms using a CAPTCHA [PHP]
- Basic Form Handling in PHP [PHP]
- Measuring password strength [PHP]
- Creating a CAPTCHA with no Cookies [PHP]
Send a message to The Art of Web:
press <Esc> or click outside this box to close