2010-09-12 4 views
1

Что я пытаюсь сделать:Несколько входов в PHP

  1. У нас есть один вход на странице
  2. Нажимаем кнопку «Добавить» и еще один вход добавляет после первого
  3. On submit мы получаем все свои значения и добавляем их в массив.

Как добавить дополнительные входы на страницу (с jquery), а затем получить их содержимое в php?

+0

Определение "входы" пожалуйста. Неясно, что означает «вход» – spender

ответ

5

Вам не нужно явно вводить входы в массив. Если вы правильно назовете поля ввода, PHP автоматически проанализирует их в массиве.

HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>jQuery dynamic input sample</title> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> 
<script type="text/javascript"> 

    // Input adding function 
    function addInput() { 
     $('#inputs').append('<p><input type="text" name="input[]"></p>'); 
    } 

    // Event handler and the first input 
    $(document).ready(function() { 
     $('#adder').click(addInput); 
     addInput(); 
    }); 

</script> 

    </head> 
    <body> 
     <form id="form" method="post" action="jquery.php"> 
      <a id="adder" href="#">Add Input</a> 
      <div id="inputs"> 
      </div> 
      <input type="submit" /> 
     </form> 
    </body> 
</html> 

PHP

foreach ($_POST['input'] as $key => $value) { 
    echo "$key $value"; 
} 
3

Может быть, это будет работать (если я правильно понял вопрос правильно)

$('#add').click(function(){ 
    $(this).before('<input name="array[]"/>'); 
}); 

и я PHP

<?php 
if (isset($_GET['array'])) { 
    for ($i=0; $i<count($_GET['array']); $i++) { 
    echo "array[$i] -> {$_GET['array'][$i]}"; 
    } 
} 
?> 
+0

имя [] - это означает массив входов? – James

+0

Да, это способ, которым это работает, вы можете увидеть в руководстве по php: http://php.net/manual/en/language.variables.external.php – jcubic

1

Я отправил это на подобный вопрос, хотя это один имеет дело только с одним входом это клонирование, а не несколько. Так что в принципе, вы HTML бы быть что-то вроде:

<form id="my_form"> 
    <input name="my_input[1]" id="my_input[1]"> 
</form> 
<a href="#" id="add_input">Add one more</a> 

И в JQuery для него будет выглядеть следующим образом:

$("#add_input").click(function(event) { 
    // Get the number of current inputs and set the new count ... 
    var inputCount = parseInt($("input[id^=my_input]").size()); 
    var newInputCount = inputCount++; 

    // ... then create new clone based on the first input ... 
    var newInput = $("#my_input[1]").clone(); 

    // .. and do the cleanup, make sure it has 
    // an unique ID and name for server-side parsing 
    newInput.attr('id', 'my_input[' + newInputCount + ']').attr('name', 'my_input[' + newInputCount + ']').val(''); 

    // .. and finally insert it after the last fieldset 
    newInput.insertAfter("#my_input[" + inputCount + "]"); 
    event.preventDefault(); 
}); 

Затем, на стороне PHP, $_POST['my_input'] будет массив из всех добавил значения полей, и их легко перебирать с помощью foreach(), например.

Надеюсь, это поможет!

Смежные вопросы