Home > other >  Remove every even line from textarea using jQuery
Remove every even line from textarea using jQuery

Time:10-05

I am having a textbox with some values in it. Now I want to remove every even line value from the textarea on click of a button. Please look at my code and suggest me how can I do it correctly.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="dinput">
10.3    137
10.9    394 <!--remove this-->
11.5    847
12.2    394 <!--remove this-->
12.9    930
13.4    940 <!--remove this-->
14.1    368
14.8    849 <!--remove this-->
15.4    563
</textarea>
<input type="button" value="Filter Data" >
<script>
$(".filterdata").click(function(){
  const txtar = $('#dinput').val();
  txtar.find(":even").remove();
  $('#dinput').val(txtar.html());
});
</script>

CodePudding user response:

Split the textarea value to an array of strings using newline character (\n) as separator. Remove odd indexes from array using Array.filter() function. Re-join array elements to string and set as textarea value.

$(".filterdata").click(function() {
  const txtar = $('#dinput').val();

  let lines = txtar.split('\n');

  let evenLines = lines.filter(function(v, i) {
    // check the index is odd
    return i % 2 == 0;
  });

  $('#dinput').val(evenLines.join('\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="dinput">
10.3    137
10.9    394 <!--remove this-->
11.5    847
12.2    394 <!--remove this-->
12.9    930
13.4    940 <!--remove this-->
14.1    368
14.8    849 <!--remove this-->
15.4    563
</textarea>
<input type="button" value="Filter Data" >

  • Related