Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove every even line from textarea using jQuery

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" class="filterdata">
<script>
$(".filterdata").click(function(){
  const txtar = $('#dinput').val();
  txtar.find(":even").remove();
  $('#dinput').val(txtar.html());
});
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" class="filterdata">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading