Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Set input type="color" required

I need to set required value for <input type="color"/>. I tried to add required="required" but it does not work. I think that it happens in this way because black is already set as default color. (Here required means that user must open color picker and choose necessary color even if it is black.)

like image 998
MyName Avatar asked Sep 08 '26 11:09

MyName


2 Answers

Input type color picker's UI has no required features other than accepting simple colors as text. Color type always have value "black" as default. Anyway, you can validate via script.

var color = document.getElementById("color");
var inputColor = document.getElementById('colorCode');

//check color input if not empty print value
if (color.value) {
  inputColor.innerHTML = color.value;
}


color.addEventListener("change", function() {
  var code = this.value;
  inputColor.innerHTML = code;
})
<input id="color" type="color">

<p id="colorCode"></p>
like image 157
VIJAYABAL DHANAPAL Avatar answered Sep 11 '26 00:09

VIJAYABAL DHANAPAL


This a workaround solution involving jquery.

var picked = false;

$("#color-picker").click(function(){
  picked = true;
});

function validateForm() {
  if (!picked) {
    //code to tell user they didn't pick a color e.g. alert("Please pick a color")
  }
  return picked;  
}
<form onsubmit="return validateForm()">
  <input type="color" id="color-picker"/>
  <input type="submit" value="submit"/>
</form>
like image 25
Cole Faraday Avatar answered Sep 11 '26 01:09

Cole Faraday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!