udexter
udexter

Reputation: 2347

Handle dynamically create inputs with jQuery (/ PHP)

I've a website where the user have to add as much as he wants <input />, like:

Company: <input type="text" name="company[]" /> Participation: <input type="text" name="participation[]" />
Company: <input type="text" name="company[]" /> Participation: <input type="text" name="participation[]" />
Company: <input type="text" name="company[]" /> Participation: <input type="text" name="participation[]" />

In my PHP backend I check if all works, and I will also use jQuery Validation, but if something go wrong, how can I rewrite this dynamically added forms?

Thank you in advance!!!

Upvotes: 0

Views: 453

Answers (2)

Felix Kling
Felix Kling

Reputation: 816324

I think I got it now. You can recreate the form elements with PHP. You get all the input values in $companies = $_GET['company']. It contains an array of values.

If you want to recreate the form elements, you can loop over this array (assuming you somehow sanitized the input), example:

<?php
// $companies and $participations should have the same length
$companies = $_GET['company'];
$participations = $_GET['participation'];

// sanitizing, validation
//...

$count = count($companies);
?>

<?php for($i = 0; $i < $count; $i++): ?>
    Company: <input type="text" name="company[]" value="<?php echo $companies[i]; ?>"/>
    Participation: <input type="text" name="participation[]" value="<?php echo $participations[i]; ?>"/>
<?php endfor; ?>

Upvotes: 1

TNC
TNC

Reputation: 5386

You can store the form in some sort of session data (pass the form as a string to PHP or save the form string to a cookie). And then you can rewrite after submission if needed.

Upvotes: 1

Related Questions