开发者

Codeigniter and jQuery for dynamical inputs

This is my first question, i would be very pleased if you can help me.

I have to catch the values of a set of dynamic inputs, i am generating the inputs with jQuery. I dont know if it’s a good solution to use the same name for all with brackets at the end like this:

<!-- f开发者_C百科irst set of entries -->
<input type="text" name="nombre_contacto[]">
<input type="text" name="mail_contacto[]">

<!-- second set of entries -->
<input type="text" name="nombre_contacto[]">
<input type="text" name="mail_contacto[]">

<!-- etc... -->  

Or just use a counter at the end of the name, like this:

<!-- first set of entries -->
<input type="text" name="nombre_contacto1">
<input type="text" name="mail_contacto1">

<!-- second set of entries -->
<input type="text" name="nombre_contacto2">
<input type="text" name="mail_contacto2">

<!-- etc... -->  

How i can catch every single item at my controller? it’s this possible?

Thanks!


Your best bet is definitely to use an array, as you are doing in your first example.

To get all the results, something like this will work:

$names = $this->input->post('nombre_contacto');
$emails = $this->input->post('mail_contacto');

Both variables are now arrays, their values are whatever the user input is, and their keys are the order in which they appeared in your form.

Something like this should give you an idea:

foreach ($names as $key => $value)
{
    $contact[$key] = $value;
}
foreach ($emails as $key => $value)
{
    $contact[$key] .= ' - '.$value;
}

Now you have a new array whose values look like: John Smith - jon@smith.com

This is just an example, I don't know what you're doing with the values.

One more example: If for some reason you had to access the third name posted, you could use this:

echo $_POST['nombre_contacto'][2]; // Arrays have 0 based index, so this is #3

This is with your input names containing brackets[]. This in my opinion, is definitely the best way. You won't need to guess how many inputs there are, because it will be an array.

Just to clarify: Using brackets in your field names turns the input into an array when it hits the server, making it possible to post multiple values with the same field name. Without brackets, it will be a string value and technically a different field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜