Reputation: 117
So I made a form using JavaScript that allows the user to put in how many ever inputs they want, but I ran into two problems. The first is that if they put extra fields and don't use them I run into errors on the other side since there is no input in those fields, and the second is that they cannot go back and edit the input if necessary. I am relatively new to JavaScript so I am not sure how to fix it, but if someone could help fix the input problem by auto deleting any empty fields that aren't used when submitted and add a protocol to be able to edit the input, I would be very grateful. Thanks so much for all your help and the code is below!
Upvotes: 1
Views: 452
Reputation: 22567
I would just check for an empty string, and continue
if it is empty... trim the $address
to weed out inputs that are just spaces.
foreach ($_POST['data']['address'] as $address){
if(empty(trim($address)) continue;
$addresses[$counter] = $address;
$counter++;
}
Upvotes: 1
Reputation: 91
In your PHP you should always check to see that your request variables aren't empty before attempting to use them. The foreach loop should look more like this:
foreach ( $_POST['data']['address'] as $address ) {
if ( !empty( $address ) ) {
$addresses[$counter] = $address;
$counter++;
}
}
This will prevent the $addresses array from having empty fields.
As for the the users not being able to "go back" and edit input fields, it's not apparent from your code sample why that would be the case. If you mean you want your users to be able to change their data after it has been submitted and processed by the server you won't be able to do it with small modifications to your existing code. You'll need to add significantly more functionality to both the front and back ends.
Upvotes: 1
Reputation: 23883
There are few ways to handle this, but they involve re-structuring your application in a few ways.
Upvotes: 1