Reputation: 1550
I have a simple form that needed validation.
I did this with the empty()
function. If the validation doesn't pass it gives the user an alert. As soon as this alert is created all entered values are gone.
I would like to keep them.
This is what I did:
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<table>
<tr>
<td>
Name:<input type="text" id="name" name="name">
</td>
</tr>
<tr>
<td>
<input class="submit-button" type="submit" value="Send" name="submit">
</td>
</tr>
</table>
</form>
<?php
if($_POST["submit"]){
if (!empty ($_POST["name"])){
// do something
}else{
?>
<script type="text/javascript">
alert('U heeft niet alle velden ingevuld. Graag een volledig ingevuld formulier versturen');
</script>
<?php
}
?>
Upvotes: 10
Views: 27604
Reputation: 1
I tried the last option, but for some reason it didn't work on my end. Maybe I did it wrong, but I just added the line above in my html file of the contact form.
Upvotes: -1
Reputation: 33813
Bizarrely I happen to be working on a similar thing and have been using the following to ensre that form data is available after submission of the form. It uses a session variable to store the results of the POST and is used as the value in the form field.
/* Store form values in session var */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
foreach( $_POST as $field => $value ) $_SESSION[ 'formfields' ][ $field ]=$value;
}
/* Function used in html - provides previous value or empty string */
function fieldvalue( $field=false ){
return ( $field && !empty( $field ) && isset( $_SESSION[ 'formfields' ] ) && array_key_exists( $field, $_SESSION[ 'formfields' ] ) ) ? $_SESSION[ 'formfields' ][ $field ] : '';
}
/* example */
echo "<input type='text' id='username' name='username' value='".fieldvalue('username')."' />";
Upvotes: 6
Reputation: 5779
Pass that entered value as a default value to input:
<input type="text" id="name" name="name" value="<?php echo isset($_POST["name"]) ? $_POST["name"] : ''; ?>">
Upvotes: 17
Reputation: 12236
The easiest way would be to this for every input field:
<input type="text" id="name" name="name" value="<?= isset($_POST['name']) ? $_POST['name'] : ''; ?>">
It checks if you already submitted the form once, if so put the value in the textbox.
Upvotes: 2