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">
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">
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">
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">
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">
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">