Append line and labels depending on textarea values jQuery (Reduce repeatability)

Dinesh

I have made some code but problem is that I need to use jQuery append again and again for every line. I am not sure that how can I make it short so that as I enter values in textarea, it automatically add or delete lines as many as required (because this code will be difficult if I have 100 or 200 lines to append).

$(document).ready(function() {
  $('.position').bind("change keyup input", function() {
    var pos = $('.position').val().split(',');
    var hght = $('.height').val().split(',');
    var lbl = $('.label').val().split(',');
    $('.peak').remove();
    $('.matchi').append("<div class='peak' style='left:" + pos[0] + "%;height:" + hght[0] + "%'>" + lbl[0] + "</div>").append("<div class='peak' style='left:" + pos[1] + "%;height:" + hght[1] + "%'>" + lbl[1] + "</div>").append("<div class='peak' style='left:" + pos[2] + "%;height:" + hght[2] + "%'>" + lbl[2] + "</div>").append("<div class='peak' style='left:" + pos[3] + "%;height:" + hght[3] + "%'>" + lbl[3] + "</div>")
  });
});
.peak {
  background: red;
  height: 100%;
  width: 0.5%;
  position: absolute;
  bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Kinglish

you can map() the compiled html based on the .position value

$(document).ready(function() {
  $('.position, .height, .label').on("input", function() {
    var pos = $('.position').val().split(',');
    var hght = $('.height').val().split(',');
    var lbl = $('.label').val().split(',');
    $('.peak').remove();
    let html = pos.map((p, i) => `<div class='peak' style='left:${pos[i]}%;height:${hght[i]}%'>${lbl[i]?lbl[i]:''}</div>`);
    $('.matchi').html(html)

  });
});
.peak {
  background: red;
  height: 100%;
  width: 0.5%;
  position: absolute;
  bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related