Pass variables with same name to PHP

4

I can not get the field return in PHP, when I enter more than 01 in quantity .... can anyone help me?

$(function() {

    var input = $('<input name="cp1" id="cp1" type="text" />');
    var input2 = $('<input name="cp2" id="cp2" type="text" />');
    var newFields = $(''); var newFields2 = $('');

    $('#qty').bind('blur keyup change', function() {
        var n = this.value || 0;
        if (n+1) {
            if (n > newFields.length) {
                addFields(n); } else {
                removeFields(n);
            }
          if (n > newFields2.length) {
                addFields(n); } else {
                removeFields(n);
            }
        }
    });

    function addFields(n) {
        for (i = newFields.length; i < n; i++) {
            var newInput = input.clone();
            newFields = newFields.add(newInput);
            newInput.appendTo('#newFields');
        }
        for (i = newFields2.length; i < n; i++) {
            var newInput2 = input2.clone();
            newFields2 = newFields2.add(newInput2);
            newInput2.appendTo('#newFields2');
        }
    }

    function removeFields(n) {
        var removeField = newFields.slice(n).remove();
        newFields = newFields.not(removeField);

        var removeField = newFields2.slice(n).remove();
        newFields2 = newFields2.not(removeField);
    }
});
#newFields input {
    display:block;
}
#newFields2 input {
    display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><label>Quantidade</label></td><td><inputtype="number" min="0" max="10" id="qty" name="qty" /></td></tr>
         <tr><td><label>Campo01</label></td><td><label>Campo02</label></td></tr>
         <tr><td><div id="newFields"></div></td><td><div id="newFields2"></div></td></tr>
  </table>
    
asked by anonymous 03.07.2015 / 21:42

1 answer

4

To get all values of some inputs that have the same name, you need to add brackets in the name attribute, so when that field arrives it will come as an array.

To fix, add the brackets when multiplying the fields:

$(function() {

    var input = $('<input name="cp1[]" id="cp1" type="text" />');
    var input2 = $('<input name="cp2[]" id="cp2" type="text" />');
//... demais código

To verify that the values are correct you can use the print_r () function in the code main does not forget to do a validation if the array is filled and make a foreach.

if(count($_POST['cp1']) > 0){
  foreach($_POST['cp1'] as $item){
   echo 'Itens selecionado: '. $item .'<br>';
 }
}
    
04.07.2015 / 00:29