topSearchDesign
topSearchDesign

Reputation: 23

Handling errors on php contact form

The below code is working great for handling errors for text fields in my contact form, but how do I get this same method to work for dropdown select option boxes and textareas?

<input type="text" name="name" value="<?php if($errors){echo $name;} ?>" id="name" size="30" />

For example:

<textarea name="message" value="<?php if($errors){echo $message;} ?>" id="message" rows="10" cols="40"></textarea>

does not work.

Upvotes: 0

Views: 429

Answers (3)

dkamins
dkamins

Reputation: 21918

This is how you should do the INPUT: it's like you have it, but you really should escape the user-provided content with htmlentities (or htmlspecialchars, etc.) in case they had quotes, brackets, etc. in the text that would be interpreted as HTML characters by the browser. That's just good practice.

<input type="text" name="name" id="name" size="30"
  value="<?php if ($errors) { echo $name; } ?>" />

This is how you should do the TEXTAREA: put the content between the textarea open/close tags. And make sure to escape it properly too.

<textarea name="message" id="message" rows="10" cols="40"
  ><?php if ($errors) { echo htmlentities($message); } ?></textarea>

This is how you might handle the SELECT tag. I've spaced out the code for readability so you can understand what's going on. Basically you just have to output selected="selected" in the OPTION element you want to be selected.

<select>
  <option value = "val1" 
    <?php if ($error && ($selval=="val1")) { echo 'selected="selected"'; } ?>
  >
    Option Label 1
  </option>
  <option value = "val2" 
    <?php if ($error && ($selval=="val2")) { echo 'selected="selected"'; } ?>
  >
    Option Label 2
  </option>
  ... (additional <option> tags here) ...
</select>

Upvotes: 1

Levi Hackwith
Levi Hackwith

Reputation: 9332

for the text area:

textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>

For the dropdown, you'll need to do something like this:

<select>
  <option value = "1" <? echo ($errror && $myposted_val == "1") ? "selected = \"selected\"" : ""; ?></option>
</select>

Upvotes: 0

Arda Xi
Arda Xi

Reputation: 2666

In the case of a textarea, you have to put the default value within the tag itself. For example:

<textarea name="message" id="message" rows="10" cols="40"><?php if($errors){echo $message;} ?></textarea>

Upvotes: 3

Related Questions