pupulate input values without each loop

let data = ["lorem", "ipsum", "dolor"];

$('input').each(function(){
  let x = $(this).attr('data-x');
  $(this).val(data[x]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='text' class='einp' data-x = 0>
<input type='text' class='einp' data-x = 1>
<input type='text' class='einp' data-x = 2>

Is it possible without each loop?

Something like:

$('input[data-x=?').val(data[?]);

Answer

You can not do that without loop, though you can optimize your code:

let data = ["lorem", "ipsum", "dolor"];
data.forEach((d,i) => $('input').eq(i).val(d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='text' class='einp' data-x = 0>
<input type='text' class='einp' data-x = 1>
<input type='text' class='einp' data-x = 2>

Leave a Reply

Your email address will not be published. Required fields are marked *