Keith Keith - 5 months ago 12
jQuery Question

find certain text in lines, then hide those lines

I am running a javascript that looks through each line. I'd like to be able to search each line and if the line contains certain text, then hide that line. So for example:

<input id="search" type="button" value="Run" />
<textarea id="main" style="height:150px;">
300 300 300
300 200 300
100 100 150
</textarea>


Javascript

$('#search').bind('click', function () {
var lines = $("#main").val().split("\n");
for (var i = 0; i < lines.length; i++) {
if($([i].contains('300' || '200'){
$(lines).css('display','none');
}
}

});


The code breaks the lines, so in this instance its 3 rows. But how do I tell it to find certain text from each row and to not display that row instead of just taking out the number. So from above the output would be:

100 100 150

Answer

You need to replace the whole textarea value. Since textarea only contains text there is no inner html for each line that can be hidden or styled in any way...it's all or none

Following filters the split array then joins it back using line break as delimiter

$('#search').on('click', function() {
  $("#main").val(function(_, oldVal) {   
    return oldVal.split('\n').filter(function(str) {
      return str.indexOf('200') === -1 && str.indexOf('300')=== -1
    }).join('\n');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="button" value="Run" />
<textarea id="main" style="height:150px;">
  300 300 300
  300 200 300 
  100 100 150
</textarea>