динамически добавлять текстовые поля с помощью PHP - PullRequest
0 голосов
/ 16 февраля 2012

Я пытаюсь создать форму, которая позволяет пользователю добавлять или удалять входные данные (текстовое поле) в форму, если они нажимают кнопку «+» или «-».

Прямо сейчас это позволит мне добавить только один блок (и удалить его), но я не могу добавить ничего больше.

РЕДАКТИРОВАТЬ - я получил его для работы с помощью 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>';
?>  

1 Ответ

3 голосов
/ 16 февраля 2012

Вам нужно сохранить значение $ 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>';   
?>  

Я не проверял это, только чтобы показать вамидея, стоящая за этим.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...