简体   繁体   中英

How can I clear a form after validation?

I'm having trouble clearing out the form after hitting submit and validating. There are three parts to this form. HTML, JS, and the PHP. The form submits and validates correctly but fields don't clear out after. I've tried multiple ways to get it to clear but I'm having no luck.

    <form id="formR" name="formR">
    <input type="hidden" name="q" id="q" value="formR">
    <input type="hidden" name="zip" id="zip" value="12345">
    <p>
    <label>
    <input name="Name" type="text" placeholder="Name" id="name" onBlur="if(this.value=='') { this.value='Your Name' }" onFocus="if(this.value=='Your Name') { this.value='' }" value="Your Name"> 
    </label><br>
    <label>
    <input name="email" type="text" placeholder="E-mail" id="email" onBlur="if(this.value=='') { this.value='E-mail' }" onFocus="if(this.value=='E-mail') { this.value='' }" value="E-mail"> 
    </label><br>
    <label> 
    <input name="phone" type="text" placeholder="Phone Number" id="phone"  maxlength="10" onBlur="if(this.value=='') { this.value='Phone Number' }" onFocus="if(this.value=='Phone Number') { this.value='' }" value="Phone Number">
    </label><br>
    </p>
    <input name="quote" id="quote" type="hidden" value="Recreational" />
    <input name="Submit" type="button" value="Submit" onClick="validateForm()">
    </form>
  function isNumberKey(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
  }

  function updateZip ()
  {
    document.getElementById('zip').value = document.getElementById('zipcode').value;
  }

  function validateForm()
  {
    if(document.getElementById('name').value.length > 0 && document.getElementById('email').value.length > 0 && document.getElementById('phone').value.length > 0 && document.getElementById('name').value != 'Name' && document.getElementById('email').value != 'E-mail' && document.getElementById('phone').value != 'Phone Number')
    {
        if((document.getElementById('email').value.indexOf('@') != -1) && (document.getElementById('email').value.indexOf('.') != -1))
            {
            subForm();
            return true;
        }
        else    
        {
            alert('Please enter a valid email address!');
            return false;
        }
    }
    else
    {
    alert('Please enter all your information in first!');
    return false;
    }
  }

  function subForm()
  {

    //var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;  //alert (dataString);return false;  
$.ajax({  
type: "POST",  
url: "sendEmail2.php",  
data: $("#formR").serialize(),
success: function(msg) { 
showNotification({
message: msg,
type: "success",
autoClose: true, 
duration: 10
})
}
});  
return false; 
$( "formR" )[ 0 ].reset(); 
}   

Plus there is a php code associated so I'm not sure if this is the reason why the form is not clearing. Maybe i'm putting it in the wrong place?

<?php
//Email sender...
//Config
`$emailTo = 'preintel@gmail.com';
$ip = $_SERVER['REMOTE_ADDR'];
if($_POST['q'] == 'formR')
{
//verify ip address:
$validateIP = true;
try{
$cont = file_get_contents("logs/formR.txt");
$lines = explode("\n",$cont);
foreach($lines as $s)
{
    if(strpos($s,$ip) !== false)
    $validateIP = false;
}

if($validateIP == false)
echo "A request has already been made with IP address: ".$ip.". Please wait until we contact you!";
}
catch(Exception $e)
{
    echo "An error occurred, please make sure your ip address is not masked!";
}

$name = $_POST['Name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$quote = $_POST['quote'];
$headers = "From: " . strip_tags($_POST['email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
//$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$subject = "New Quote Request From: ".$name;
$message = "<h3>A quote has been requested:</h3><hr/>Name: ".$name."<br/>Email: ".$email."<br/>Phone Number: ".$phone."<br/>Quote: ".$quote."<br/><br/><br/>Request Time: ".date("Y-m-d H:i:s")."<br/>Requesting IP: ".$ip;
if($validateIP)
{
    if(mail($emailTo, $subject, $message, $headers))
    {
        echo "Thank you, your quote will be processed! We will contact you shortly.";
        //Write ip to log file...
        $file = 'logs/formR.txt';
        $current = file_get_contents($file);
        $current .= $ip." - ".date("d/m/y : H:i:s", time())."\n";
        file_put_contents($file, $current); 
    }
    else
    echo "An error occurred sending your email, please try again later!";
}
}
else
echo "Oops! An error occurred... Please email us at: ".$emailTo;
?>

You should be doing:

$("#formR" )[0].reset(); //<--forgot the # because that's the form's ID

And you probably don't need the [0] in: $("#formR" )[0].reset();

And put that line before the return statement - you currently have it after.

This is assuming you have some sort of jquery plugin that exposes a "reset" function- I haven't seen this before in the core jquery library.

After validating and submitting a form, if you want to reset the values to their default values (the values they originally had), you can simply manually set the php variables to those default values. So, if the values were initially empty, set the variables to "" and attach them to the form again.
If you are using AJAX to submit the form, you can use JavaScript to clear the contents as well or you can simply refresh the page. That'll take care of it.
Unless there's something specific you are having problems with, resetting a form shouldn't pose any trouble.

Hope this helps.

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