Pyreal Pyreal - 3 months ago 8
CSS Question

Highlight words from multiple input fields simultaneously

I have a problem i'm working on, my program will highlight words if typed in an input field. It wont highlight words from both.(Example Input1 type "Test1", Input2 type "Test2") is there a way to keep the highlighted words active from one field when the user switches to another?

JSBIN: http://jsbin.com/xovisayaso/edit?html,css,js,output

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>


<title>JS Bin</title>
</head>
<body>



<div id="listArray">
<span>Test1</span>
<span>Test2</span>
<span>Test3</span>
</div>

<input type="text" class="form-control" id="userArray">
<input type="text" class="form-control" id="userArray2">

</body>
</html>

<script
$("#userArray, #userArray2").on('change keyup paste', function() {

var input = $(this).val().toLowerCase().split(" ");
$('#listArray span').each(function(){
$(this).removeClass('active');
if( $.inArray( $(this).text().toLowerCase(), input ) != -1 ) {
$(this).addClass('active');}});});
</script>

<style>#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: green; }
}
</style>

Answer

You can achieve the desired effect by removing the active class whenever the text changes and then checking against both inputs:

$("#userArray, #userArray2").on('change keyup paste', function() {
  $('#listArray span').removeClass('active');
  $('input').each(function() {
    var input = $(this).val().toLowerCase().split(" ");
    $('#listArray span').each(function() {
      if ($.inArray($(this).text().toLowerCase(), 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: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="listArray">
  <span>Test1</span> 
  <span>Test2</span>
  <span>Test3</span> 
</div>

<input type="text" class="form-control" id="userArray">
<input type="text" class="form-control" id="userArray2">