Pass variables with same name to PHP

Asked

Viewed 176 times

4

I can’t catch the return of the fields in PHP, when I enter more than 01 in quantity.... someone can 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><input type="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>

1 answer

4


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

To correct, add the square 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 check if the values are correct you can use the function print_r(), in the main code do not forget to do a validation if the array is filled and do a foreach.

if(count($_POST['cp1']) > 0){
  foreach($_POST['cp1'] as $item){
   echo 'Itens selecionado: '. $item .'<br>';
 }
}
  • Thanks rray, that’s right! It worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.