User Has Choice Of Two Inputs But Only One Is Required.

- 1 answer

For the creation of a paint manufacturer website, the product page is required to give the user the option of either entering a RAL colour code or choosing a colour using a colour selector.

To do this, I've used:

<p class="line-item-property__field">
  <label for="ral-colour-code">RAL Colour Code</label>
  <input required class="required" id="ral-colour-code" type="text" name="properties[RAL Colour Code]">

<p class="line-item-property__field">
  <label for="choose-a-colour">OR Choose a colour</label>
  <input  id="choose-a-colour" type="color" name="properties[Choose a colour]">

This achieves the main goal, in that the user's choice of colour is included in the confirmation order that the company receives. However, my concern is that in some cases a user may pick a colour using the selector, then input an accurate colour code - both of which will be included in the confirmation. I'd imagine the best practice would be to disable one input upon entry of text into the other input, however it would need to be clear to the user which of the two options were going to be the one applied to their order.

What' I've attempted: After doing a bit of digging I found a similar question answered here. So I attempted that:

jQuery(function ($) {
 var $inputs = $('properties[RAL Colour Code],properties[Choose a colour]');
  $inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
  $inputs.not(this).prop('required', !$(this).val().length);

This returned the following error:

Error: Syntax error, unrecognized expression: properties[RAL Colour Code],properties[Choose a colour]

In addition to the error, I think this might not be the solution I'm looking for, as that simply removes the required tag, but presumably the user stil has the option to fill in both.



Try this:

<input type="text" id="choose" />
<input type="text" id="write" />

and jQuery:

$("#choose, #write").keyup(function(){
  if($("#choose").val() != "") {
  }else if($("#write").val() != "") {

Here is working fiddle for you

New fiddle that covers your needs. Clear color button is added, your ids are used and event for input type="color" has changed to .change()