0

I have an array of strings. How can I put each value into each field in HTML, index by index?

const pid = [ "688", "500", "450" ];
<input type="text" class="field_pid">
<input type="text" class="field_pid">
<input type="text" class="field_pid">
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • You can use `map`. – Vilas Oct 23 '19 at 05:59
  • Some closely related variations: Reaching the current element (and its properties): [How to reach the element itself inside jQuery’s `val`?](/q/16710521/4642212); Mapping the current value (e.g. via a function, or appending something to it): [Modify the value of each textfield based on original value using jQuery](/q/24725927/4642212), and [Append text to input field](/q/841722/4642212). – Sebastian Simon Feb 08 '22 at 05:08

4 Answers4

1

Using val( function )

The .val() method allows setting the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value

var pid = ["688", "500", "450"];

$(".field_pid").val((i) => pid[i]);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

<input type="text" class="field_pid">
<input type="text" class="field_pid">
<input type="text" class="field_pid">
User863
  • 19,346
  • 2
  • 17
  • 41
0

You can try this code. It works for me:

$(function() {
  var pid = ['688', '500', '450'];
  var l = pid.length;
  var i = 0;
  while (i < l) {
    $('.field_pid').eq(i).val(pid[i]);
    i++;
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="field_pid">
<input type="text" class="field_pid">
<input type="text" class="field_pid">
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
Aksen P
  • 4,564
  • 3
  • 14
  • 27
0

You have 2 ways either you can map over the classes because same class stored in array format or you have already array list pid , i maped over array pid

var pid = ['688', '500', '450'];
$(document).ready(function(){
pid.map((value , key)=>{
$('.field_pid').eq(key).val(pid[key]);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <input type="text" class="field_pid">
<input type="text" class="field_pid">
<input type="text" class="field_pid">
DEEPAK
  • 1,364
  • 10
  • 24
0

Use forEach and eq:

$(() => {
  const pid = ["688", "500", "450"];
  
  pid.forEach((num, idx) => $(".field_pid").eq(idx).val(num));
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="text" class="field_pid">
<input type="text" class="field_pid">
<input type="text" class="field_pid">
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79