moody moody - 3 months ago 15
HTML Question

replace text in textfield with colored text, jquery

I have a textfield with filled value. It contains 'XXXX' and i would like to highlight only the 'XXXX' so the user can notice, that the XXXX must be replaced by a value. How can I get the value, take only the 'XXXX' and replaced it with the same value, but colored.

Answer

You can use Div Element :

<html>
    <title>This is test</title>
    <head>
        <style>
            .highlight {
                background-color: yellow;
            }
            div {
                    -moz-appearance: textfield;
                    -webkit-appearance: textfield;
                    background-color: white;
                    background-color: -moz-field;
                    border: 1px solid darkgray;
                    box-shadow: 1px 1px 1px 0 lightgray inset;  
                    font: -moz-field;
                    font: -webkit-small-control;
                    margin-top: 5px;
                    padding: 2px 3px;
                    width: 398px;    
            }
        </style>
    </head>
    <body>
        <div class="txt" contenteditable="true"> I am XXXX.</div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>

           $(document).ready(function(){

               $txt = $(".txt").text();

               $newTxt = $txt.replace(/XXXX/gi,"<span class=highlight>XXXX</span>"); 

               $(".txt").html($newTxt);

           })
        </script>
    </body>
</html>