HTML5 input color's default color

前端 未结 7 2102
感情败类
感情败类 2021-02-01 01:16

The input type=\"color\" has a default color which is black: #000000.

Even if I give it an empty value...

相关标签:
7条回答
  • 2021-02-01 01:55

    The answer can be twofold.

    1. For display purposes, yes, you can set a default color just by setting the value of the input to the color you want. You can see varieties of this in the answers on this page.
    2. Technically, no. It is not possible to send an empty value as color through POST. The POSTed value will always default to #000000 or the color which you have set default (as mentioned in 1.).

    After some thought on this, perhaps a practical solution for this might be to choose #010101 as a reference to null or false or whatever. This leaves room for some jQuery (or javascript) to make it less likely that this value can be set.

    <input type="color" name="myColor" required="" />
    

    For instance, on one hand the color inputs that are set to required can be given the value #010101 at event load. And to be sure, prevent users selecting the color #010101.

    (function($){
    
      "use strict";
    
      // Set all required color input values to #010101.
      $(window).on("load", function() {
        $("[type='color'][required]").val() == "#010101";
      });
    
      $("[type='color'][required]").on("change", function() {
    
        // Prevent users selecting the color #010101.
        if($(this).val() == "#010101") {
          $(this).val() == "#000000";
        }
      });
    
    })(jQuery)
    

    At the time of server-side validation, #010101 is considered as empty (or false, etc.).

    <?php
    $color = htmlspecialchars($_POST['myColor']);
    if($color == "#010101") {
      // Do variable empty routine
    } else {
      // Do variable has value routine
    }
    ?>
    

    *Now you can be pretty sure to know if the user has set the value, as long as the UA has javascript capabilities.

    The drawback is the setting of the color on load. Reload with a pre-set value is not possible this way. Perhaps this can be improved with the use of sessionStorage.*

    But the real point is: Why am I doing this? I don't think it should be neccessary, the default value of #000000 is the single deviation from the normal workings of an input type. Except for the range input type, which also has an optional default value, this color input type is very different.

    0 讨论(0)
提交回复
热议问题