Dynamically php add/remove inputs

Asked

Viewed 455 times

1

I am creating a form where when filling in, the user will add more fields dynamically, so far I have already, but I would like to separate the value of each field added to send the separate data in PHP, because all are with the parameter name with mytext[].

Follow the code below:

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remover</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="add_field_button">Adicionar novo campo</button>
    <div><input type="text" name="mytext[]"></div>
</div>

  • I don’t understand Leno. You want to receive the values separately, but when you put the myText[], at the time of POST, you receive this parameter as an array. It’s not enough? You want to try each field as a new value in the post?

1 answer

1

If I understand your question, just put the value of x in the name.

$(wrapper).append('<div><input type="text" name="mytext"'+x+'/><a href="#" class="remove_field">Remover '+x+'</a></div>');
        }
    });

Browser other questions tagged

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