2016-04-08 6 views
-1

どのように配列値を取得し、既存のテキストフィールドに値を設定できますか? 例として、配列には5つの値があり、5つのテキストフィールドがあります。フォームフィールドに配列を設定する

Array [ tom, Matt, Lucy, Suzanna, Hank ] 
<input type="text" name="firstName" value=""> 
<input type="text" name="firstName" value=""> 
<input type="text" name="firstName" value=""> 
<input type="text" name="firstName" value=""> 
<input type="text" name="firstName" value=""> 
+0

入力をループし、配列から次の項目を追加する関数を記述します。 – WillardSolutions

答えて

0

あなたは、全体として、配列の反復処理、または単にあなたの<input>要素を反復処理し、オフにポップするには、以下のようなものを使用することができるはず1

1

により、すべての配列値1にアクセスすることができましたそれぞれの名前彼らはそれぞれ排出されるまで:

// Your array 
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank']; 

// Loop through the array and target the next available textbox 
for(var input in document.getElementsByName('firstName')){ 
    // If there are any names to use, use one 
    if(array.length > 0){ 
     // Pop the next name off of your array and set the value 
     // of your textbox 
     input.value = array.pop(); 
    } 
} 

あなたが実際に値を設定するには、上記の例を使用してすべての問題を持っている場合、あなたは常に物事を処理するために、わずかに異なるループを使用することができます。

// Your array 
var array = ['Tom', 'Matt', 'Lucy', 'Suzanna', 'Hank']; 

// Store your input elements 
var inputs = document.getElementsByName('firstName'); 
// Loop through the array and target the next available textbox 
for(var i = 0; i < inputs.length; i++){ 
     // If there are any names to use, use one 
     if(array.length > 0){ 
      // Pop the next name off of your array and set the value 
      // of your textbox 
      inputs[i].value = array.pop(); 
     } 
} 

あなたがsee a working example in action hereできると何が提供されたデータを使用して、出力は以下のようになります。

enter image description here

0

あなたはさまざまな方法の束にそれを行うことができます。 例えば

その後、あなたがそれらに価値を追加するためにjqueryのまたはJavaScriptを使用することができ、それらに

<input type="text" class="damn" name="firstName" value=""> 
<input type="text" class="damn" name="firstName" value=""> 
<input type="text" class="damn" name="firstName" value=""> 
<input type="text" class="damn" name="firstName" value=""> 
<input type="text" class="damn" name="firstName" value=""> 

を値を追加するためのフィールドにクラスと使用jqueryのを与える:

var currIndex = 0; 
$(document).ready(function(){ 
    $(".damn").each(function(){ 
     $(this).val(myarray[currIndex++]); 
    }); 
}); 

UPDATE:また、Rion Williamsが作成したアプローチを使用することもできます。

関連する問題