Question

I have a xhtml form with text boxes and so on. I have one box for postcode where it says, default value 119900.

<td><label for="postcode"> Post Code (default "119900"): </label></td>
<td><input type="text" value= "119900" id="postcode" name="postcode" size=6 maxlength=6/>

As shown by the code above, that is done by putting the value as 119900. What i want do is, to retain the input in the box if someone changes it and submits the form. So if i change it from 119900 to 110055 and click submit, 110055 should stay in the box instead of 110099. Is there anyway i can do that? i have tried

<td><label for="postcode"> Post Code (default "119900"): </label></td>
<td><input type="text" value= "119900"
value="<?php echo (isset($_POST["postcode"]) ? $_POST["postcode"] : ''); ?>"
id="postcode" name="postcode" size=6 maxlength=6/>

doesnt seem to work.

Était-ce utile?

La solution

You're so close. Instead of a blank default value in your ternary statement, just put your default value (and ditch your invalid repetition of the value attribute).:

<input type="text"
value="<?php echo (isset($_POST["postcode"]) ? $_POST["postcode"] : '119900'); ?>"
id="postcode" name="postcode" size=6 maxlength=6/>

You can also shorten this a bit:

<input type="text" value="<?= ($_POST["postcode"]) ?: '119900'); ?>"
id="postcode" name="postcode" size=6 maxlength=6/>

(For anyone complaining about the short tag usage, the minimum supported version of PHP is 5.4 which has them enabled by default. So unless you are targeting older versions of PHP and/or plan to distribute the code this is fine to do).

Autres conseils

You are use two value field that's why it not working. Try this one:

<input type="text" value="<?= (isset($_POST["postcode"]) ? $_POST["postcode"] : '') ?>"
id="postcode" name="postcode" size=6 maxlength=6/>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top