javascriptjqueryhtmlmaskedinput

How to make two maskedinput work on a single input?


I'm creating a color picker, but I want to let the possibility to the user to choose transparent as color, I'm using the masked input to filter hexadecimal inputs and letters at the same time, everything in one input.

You can see on JSFiddle : https://jsfiddle.net/Lindow/60u9wygp/7/

Whenever the user clicks "transparent" button the input's value should be 'None' and whenever he clicks the color there should be the hex color in the input.

The snippet is quite long but there's isn't much going on, so it is really simple to understand.

$(document).ready(function() {

  $('.colorbox').click(function(element) {
    $(".colorpickertext").val(element.target.value)
    $("#colorpicker").css({
      'background': element.target.value
    });
  });

  $('.colorbox-transparent').click(function(element) {
    $(".colorpickertext").val('None')
    $("#colorpicker").css({
      'background': '#fafafa'
    });
  });

  $(".colorpickertext").keyup(function(element) {
    $("#colorpicker").css({
      'background': element.target.value
    });
  });

  var hexadecimal = [{
    "mask": "\\#hhhhhh"
  }, {
    "mask": "llll"
  }];
  $('.colorpickertext').inputmask({
    mask: hexadecimal,
    greedy: false,
    definitions: {
      'h': {
        validator: "[A-Fa-f0-9]",
        cardinality: 1
      },
      'l': {
        validator: "[a-zA-Z ]",
        cardinality: 1
      },
    }
  });
});
button {padding:20px;}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div id="colorpicker">input below should be "None" on transparent button click</div>
<button class="colorbox" value="None" style="background:#ffffff;">transparent</button>
<button class="colorbox" value="#ffbf00" style="background:#ffbf00;"></button>
<input type="text" class="colorpickertext form-control" placeholder="ex: #4dadc9">

Any suggestion on how I can fix this?


Solution

  • I never used the masked input before, but I think I worked it out from the docs. You're already using two options for masks, you just have to add a third. I made a third that accepts "None":

    var hexadecimal = [{
      "mask": "N"
    }, {
      "mask": "\\#hhhhhh"
    }, {
      "mask": "llll"
    }];
    $('.colorpickertext').inputmask({
      mask: hexadecimal,
      greedy: false,
      definitions: {
        'h': {
          validator: "[A-Fa-f0-9]",
          cardinality: 1
        },
        'l': {
          validator: "[a-zA-Z ]",
          cardinality: 1
        },
        'N': {
          validator: "None",
          cardinality: 4
        },
      }
    });
    

    The order of the masks mattered - you had to look for "None" first so it wasn't filtered to just #e.