2012-05-09 4 views
1

ユーザーが特定の情報を入力できるフォームを作成しています。 デフォルトの状態は次のようになります。複数のテキストフィールドを追加して1つの文字列にまとめたHTML/PHP

<div class="options"> 
<input type="text" name="option[]" /> 
<input type="text" name="content[]" /> 
</div> 

次のような状態があるので、今、ボタンADDをクリックすることで、私は同じ名前を持つ2つの新しいフィールドを追加します。

<div class="options"> 
    <input type="text" name="option[]" /> 
    <input type="text" name="content[]" /> 
    <input type="text" name="option[]" /> 
    <input type="text" name="content[]" /> 
    </div> 

次に、PHPで最終的に以下のような文字列を作成します。

valueOfFirstOption:valueOfFirstContent,valueOfSecondOption:valueOfSecondContent 

などと同様に。理論的には無限大の入力フィールドを追加できるはずです。

私はこれを達成しようとしていますか?または、入力フィールドに固有の名前を追加する必要がありますか?

どのようなヒントが必要ですか?または、誰かが私のためのチュートリアル/サンプルコードを手に入れましたか?

ありがとうございます。

+0

は、jQueryの(追加のフィールドを追加するための)オプションデュプレットされているプロセスができますか? – iambriansreed

答えて

0

これは、余分な要素を追加するときに名前にインデックスを設定できる場合は、少し上手くなります。あなたはPOSTを受け取ったときに

<div class="options"> 
    <input type="text" name="data[0][option]" /> 
    <input type="text" name="data[0][content]" /> 
    <input type="text" name="data[1][option]" /> 
    <input type="text" name="data[1][content]" /> 
</div> 
<a href="#" onclick="addSet(); return false;">Add</a> 
<script> 
    var addSet = function() { 
     var container = document.getElementsByClassName('options')[0]; 
     var numInputs = container.getElementsByTagName('input'); 
     var numSets = numInputs/2; 
     var nextIndex = numSets; 

     var newOption = document.createElement('input'); 
     newOption.name = 'data[' + nextIndex + '][option]'; 
     container.appendChild(newOption); 

     var newContent = document.createElement('input'); 
     newContent.name = 'data[' + nextIndex + '][content]'; 
     container.appendChild(newContent); 
    } 
</script> 

はその後、あなただけのデータをループとは

$pieces = array(); 

foreach ($_POST['data'] as $set) 
    $pieces = $set['option'] . ':' . $set['content']; 
} 

// or 
for ($i = 0; $i < count($_POST['data']); $i++) { 
    $pieces[] = $_POST['data'][$i]['option'] . ':' . $_POST['data'][$i]['content']; 
} 

// then 
$compiledString = implode(",", $pieces);