views:

66

answers:

3

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.

+3  A: 

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>
Arda Xi
textarea working great now, Thank-you!
topSearchDesign
Also, since you'll probably want to know about the select box, that would be the same thing (embed the message in the option tag).
Arda Xi
A: 

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>
Levi Hackwith
+1  A: 

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>
dkamins
Selection box working as well, thanks!
topSearchDesign