tonco
tonco

Reputation: 1311

Input highlight part of text

Is there any change to have input element similar like is on my screenshot.

enter image description here

I would like to change value via javascript and highlight part of text with different color if it will be wrapped with *

Thanks for any help.

Upvotes: 0

Views: 695

Answers (1)

bjaksic
bjaksic

Reputation: 3313

You cannot do it with an input element. Here is one alternative:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    /*style it to look like input element*/
    [contenteditable] {
        border: 1px solid gray;
    } 
  </style>
</head>
<body>
<div id="contentDiv" contenteditable>sdfsdtokendfdfsdfs</div>
<br/>
<input type="button" onclick="test()" value="Click me"/>
<script type="text/javascript">
function test() {
    // this is our token
    var valueToSelect = "tokendfdf";
    var contentDiv = document.getElementById('contentDiv');

    // check if div contains wanted token
    if (contentDiv.innerHTML.indexOf(valueToSelect) >= 0) {
        // create span with wanted color
        var replaceString = '<span style="color: red">*' + valueToSelect + '*</span>';
        // replace the string with colored span
        contentDiv.innerHTML = contentDiv.innerHTML.replace(valueToSelect, replaceString);
    }   
}
</script>
</body>
</html>

Here is JS Bin example

Upvotes: 2

Related Questions