0

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[?]);
qadenza
  • 9,025
  • 18
  • 73
  • 126

5 Answers5

2

You can use jQuery.fn.val with a function. Just access the element in the data array using the value of data-x and return it. Note that it still uses a loop implicitly.

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

$("input").val(function () {
  return data[this.dataset.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>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
1

No, that is not possible with .val(). By selecting multiple inputs and setting the value on the jQuery object, you'll apply the same value to the entire collection of elements.

If you're trying to one-line it, you could do

$('input').each(function() {
  $(this).val(data[ $(this).attr('data-x') ]);
});

If you use arrow functions

$('input').each( item => $(item).val(data[ $(item).attr('data-x') ]) );
Soviut
  • 88,194
  • 49
  • 192
  • 260
1

May be something like this?

let data = ["lorem", "ipsum", "dolor"];
data.forEach((d, i) => {
  $(`input[data-x=${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>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
1

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You can use simple data binding library like knockoutjs

If you worry about adding another library and also you have skill for javascript, just google data binding in javascript. you can find many articles

Basically you have an object with property defined for each text boxes and getter and setter will bind with textbox event. so that you can have simple two way data binding mechanism.

kamprasad
  • 608
  • 4
  • 12