How to prevent forms from emptying inputs by submi

2019-09-05 06:44发布

问题:

I'm writing a form in using php and html. This form has validation control. when I submit the form all the textboxes get empty and if the user has filled for example 3 of 5 inputs , because if those two inputs he/she now has to fill those 3 inputs again. How can I prevent the form from emptying the inputs by submitting the form?

回答1:

If you validation script and form code are in this same file you can just put $_POST values into form.

<?php
$field1 = '';
$field2 = '';
...
$field5 = '';
if($_SERVER['REQUEST_METHOD']=="POST"){
    $field1 = $_POST['field1'];
    $field2 = $_POST['field2'];
    ...
    $field5 = $_POST['field5'];

    if(validation is true){
     //do something
    }
}
    ?>

    <form method="post">
       <input type="text" name="field1" value="<?= $field1 ?>" >
       <input type="text" name="field2" value="<?= $field2 ?>" >
        ...
       <input type="text" name="field5" value="<?= $field5 ?>" >
       <input type="submit" value="submit" >
    </form>

EDITED after comment RiggsFolly.



回答2:

check if form field is set in $_REQUEST array or not, print its value accordingly

<form method="post">
    <input type="text" name="field1" value="<?php echo (isset($_REQUEST["field1"])? $_REQUEST["field1"]:""?>" >
    <input type="text" name="field2" value="<?php echo (isset($_REQUEST["field2"])? $_REQUEST["field2"]:""?>" >
    ...
    <input type="text" name="field5" value="<?php echo (isset($_REQUEST["field5"])? $_REQUEST["field5"]:""?>" >
    <input type="submit" value="submit" >
</form>


回答3:

i thought of javascript:

function validateForm() {
     var x = document.forms["myForm"]["fname"].value;
     if (x == null || x == "") {
         alert("Name must be filled out");
         return false;
     }
 }

You can find all about is on: http://www.w3schools.com/js/js_validation.asp

It works great, when user lets the field empty, it will say: "Name must be filled out". The submit will do nothing until you fill that...

//sorry for bad english