Like text color of input element

I have an input token in my form, so I want each comma-separated token to have a different background color. My question is, how do I style each element by value or can I use id in the value?

I want to

  • red to use a red background,
  • blue to use a blue background,
  • green to use a green background,
  • etc.

What should I do for this? Here is my code:

<input value="red,blue,green"
       type="text"
       id="exampleInlineTags"
       class="form-control token-example-field"
       name="search"
       placeholder="Enter tags" />
+4
source share
1 answer

You cannot inherit the input style, since it involves the use of additional internal HTML tags (which is literal, you need real children!)

contenteditable DIV

function toColorTokens() {
  $(this).html( // Remove whitespaces & Create our SPAN elements
    $(this).data("value").replace(/\s/g, "").replace(/[^,]+/g, function(m) {
      return "<span style='background:"+ m +";'>"+ m +"</span>";
    })
  ); 
}

function removeColorTokens() {
  $(this).text( $(this).data("value") );
}

function storeDataValue() {
  $(this).data("value", $.trim($(this).text()));
}

$("[contenteditable]").on({
  input    : storeDataValue,    // update data-value on input
  keypress : function(e) { return e.which !== 13; }, // Prevent Enter key
  focus    : removeColorTokens, // decolorify on focus
  blur     : toColorTokens      // colorify on blur
  
}).trigger("blur");             // Do it now!
[contenteditable]{
  border:1px solid #ddd;
  padding:4px 8px;
  border-radius:3px;
}
[contenteditable]:empty:not(:focus):before{
  content:attr(data-placeholder);
  color:#888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable data-value="red,green,blue,#F00BA4" data-placeholder="Enter tags"></div>
Hide result
+2

All Articles