user3714932
user3714932

Reputation: 1353

Dynamically added input's value not being captured in Php

I have a form where I add input fields dynamically using a jquery and then submitting the values of that form using Laravel Php

My html:

<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button>
  <div>
    <input type="text" name="mytext[]">
  </div>
</div>

My script:

<script type="">
$(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">Remove</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>

The problem is that when I submit the values I've entered in the input boxes and try to capture them using the following Laravel code.

$mytext =Request::get('mytext');
dd($mytext);

Only the first value of the input I've defined in the html is captured no matter how many text inputs I add.

The output:

array:1 [▼
  0 => "Text box 1"
]

How do I solve this? Thanks

Upvotes: 0

Views: 104

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You already have a variable to count the appended inputs...
Use it!

Notice name="mytext'+x+'":

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

And also sent the x to know how many are sent.

Upvotes: 1

webmasterdro
webmasterdro

Reputation: 224

You can add different name for the each input you add.

Your HTML:

<input type="text" name="mytext[text]">

Your JS:

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
            $(wrapper).append('<div><input type="text" name="mytext[text'+  x++  +']"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
       }
});

The output will be:

"mytext" => array:4 [▼
   "text" => "Text"
   "text1" => "Text1"
   "text2" => "Text2"
   "text3" => "Text3"
]

Hope this help!

Upvotes: 2

Related Questions