Reputation: 235
I have a token input in my form, so I want every comma-separated token to have a different color background. My question is how do I style every element by value, or can I use the id in the value?
I want
What do I do to accomplish 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" />
Upvotes: 4
Views: 123
Reputation: 206008
You cannot natively style the value of an input since it presumes the use of additional inner HTML tags (which is literal, you need real child elements!)
A workaround would be using a 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>
Upvotes: 2