简体   繁体   中英

Removing Empty Fields When Submitting Form

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!

There are few ways to handle this, but they involve re-structuring your application in a few ways.

  1. Restrict the system so they can't add a new address until the previous ones are filled in.
  2. Before submitting the form, run a sanity check and remove any blank addresses, renaming the fields as needed.
  3. Convert the form to an Ajax object and submit that way. You'll need to rework the backend to make sure it accepts the JSON properly.
  4. Make your PHP smarter and better with checking/validation of incoming data.

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.

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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM