简体   繁体   中英

How do you highlight typed text when it's not static?

Example of what I'm going for.

I have two Textareas. One holds a list of single words, one per line, this list will not be the same every time.

My second text area will be used for input by the user. My goal is to highlight words in the first text area when that word is typed into the second text area. I've attached an example photo showing what I wish to accomplish.

Example: http://imgur.com/a/I27eO

My code is just pushing a list of words into the first Text area and separating them. I'm looking for help on how to highlight the desired words.

<textarea class="col-md-3" id="inputArray1" rows="20" cols="10" placeholder="Input1"></textarea>
<textarea class="col-md-3" id="inputArray2" rows="20" cols="10" placeholder="Input2"></textarea>

//holding input values for text area
var InputVar = document.getElementById("inputArray1").value;
var InputVar2 = document.getElementById("inputArray2").value;

//holding output values for text area
var OutputVar = document.getElementById("outputArray1");
var OutputVar2 = document.getElementById("outputArray2");

// takes string and breaks into substring array of words
var SplitString = InputVar.split(/[\s]+/g);

//displays list of words in 2nd text area
OutputVar.value = SplitString;

Since you tagged jQuery, here is a basic function that checks if any user words match any of the listed words:

 $("#userArray").on('change keyup paste', function() { var input = $(this).val().split("\\n"); $('#listArray span').each(function() { $(this).removeClass('active'); if ($.inArray($(this).text(), input) != -1) { $(this).addClass('active'); } }); }); 
 #list_input > div { border:4px solid; padding: 1em; margin: 1em auto; } #listArray { overflow: auto; } #listArray span { display: block; float: left; clear: left; padding:4px; margin:1px; } #listArray span.active { background: yellow; } #userArray { width: 100%; height: 150px; border: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container" id="list_input"> <div id="listArray"> <span>Lorem</span> <span>Eos</span> <span>Earum</span> <span>Tempora</span> <span>Recusandae</span> </div> <div> <textarea id="userArray" placeholder="enter words..."></textarea> </div> </div> 

jsFiddle: https://jsfiddle.net/azizn/3x3ga3tL/


Edit: you can append a list of words dynamically from a JS array using the following script:

var words = ["Test1", "Test2", "Test3","Test4"];
for (var i = 0; i < words.length; i++) {
    $('#listArray').append("<span>" + words[i] + "</span>");
}

jsFiddle: https://jsfiddle.net/azizn/3x3ga3tL/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM