2012-02-16 62 views
0

"+"または " - "ボタンをクリックすると、フォームに入力(テキストボックス)を追加または削除できるフォームを作成しようとしています。PHPを使って動的にテキストボックスを追加する

今は1つのボックスを追加するだけです(削除することもできます)が、それ以上は追加できません。

EDIT - 私はGETを使用して動作させました。あなたが興味を持っているなら、私がしたことがここにあります。

<? 
$j=1; //sets the value initially when the page is first loaded 

if($_GET['num'] >= 1){ 
    $j = mysql_real_escape_string($_GET['num'])+1; 
} 

//displays the text boxes 
echo '<table>'; 
for($i = 0; $i<$j; $i++){ 
    echo '<tr><td><input type="textbox" name="input[]"></td></tr>'; 
} 
    //displays the + and - buttons to add or remove text boxes 
$a = $j-2; 

echo '</table>'; 
echo '<a href="helplist.php?num='.$j++.' "> + </a>'; 
echo '<a href="helplist.php?num=' .$a. '"> - </a>'; 
?> 
+0

私は本当に問題が何かを理解していません。 $ jの価値は何ですか? –

+0

私のコードを編集しました。申し訳ありません。提出するたびに – user1104854

+0

、ページの読み込み、jは1に戻ります。あなたは状態を保存するか、js fortを使用する必要があります(とにかく簡単です)。 –

答えて

3

隠しフォームフィールドに$ jの値を格納する必要があります。

例:<input type=hidden value=$j name=j>

<? 
if(!isset($_POST['j'])){ 
    static $j=1; 
} 
else{ 
//j is a reference for $i in the loop. $i will loop while it is less than $j. 

if(isset($_POST['plus'])){ 
    $j = $_POST['j']+1; //by incrementing $j, $i will loop one more time. 
} 

if(isset($_POST['minus'])){ 
    if($j < 1){ //if there is only one box the user can't remove it 
     $j = $_POST['j']-1; 
    } 
} 
} 
//displays the text boxes 
echo '<form method="post"> 
<input type="hidden" name="j" value="' . $j . '"> 
<table>'; 
for($i = 0; $i<$j; $i++){ 
    echo '<tr><td><input type="textbox" name="input[]"></td></tr>'; 
    echo 'i='.$i.'<br/>'; //checking value of $i 
    echo 'j='.$j.'<br/>'; //checking value of $j 
} 
    //displays the + and - buttons to add or remove text boxes 
echo '<tr><input type ="submit" value="+" name="plus"> 
     <input type ="submit" value="-" name="minus"></tr></table></form>'; 
?> 

私はあなたにその背後にあるアイデアを表示するには、これをテストしていません。

+0

それを増やしたり、それを静的に設定するのはどうですか? – user1104854

+0

私は私の答えを編集します。 –

+0

これはループ内か他の場所に入りますか? – user1104854

関連する問題