How to "remember" selected form values ​​in PHP?

If the user refuses to check the form, then to make it easier for them, we can do this:

if(isset($_POST['submit'])) { $email = $_POST['email']; //.... } <input type="text" name="phone" value="<?php echo $phone; ?>" /> <input type="text" name="email" value="<?php echo $email; ?>" /> ... 

So, in this case, if the user did not pass the verification because he entered the email, but not the phone number, then when the page is updated after sending and warns about the missing phone, the letter (which they filled out) will already be in place and will not require the user to re-enter.

But how can I “remember” the values ​​selected by the user for the selection, radio and checkbox inputs?

+6
html php validation forms
source share
3 answers

It works the same, but this will require another work:

 <select name="whatever"> <option value="Apple">Apple</option> <option value="Banana" selected="selected">Banana</option> <option value="Mango">Mango</option> </select> Banana is selected here. <input type="checkbox" name="fruits[]" value="banana" /> Banana <input type="checkbox" name="fruits[]" value="mango" checked="checked" /> Mango <input type="checkbox" name="fruits[]" value="apple" checked="checked" /> Apple Mango and Apple are checked here 

So basically you add selected="selected" or checked="checked" to the appropriate fields when creating the form.

Another option would be to use something like jQuery to create these parameters after loading the page and preparing the DOM manipulations. Thus, you can easily make all the changes in one place without fading the code. Of course, now there is a flaw that you will need to download jQuery. And your users will need JS.

+1
source share

Here is a sample code.

 <?php $options = array('option1' => 'Option 1', 'option2' => 'Option 2', 'option3' => 'Option 3'); $myselect = 'option2'; ?> <select name="myselect"> <?php foreach($options as $key => $value) { echo sprintf('<option value="%s" %s>%s</option>', $key, $key == $myselect ? 'selected="selected"' : '', $value); } ?> </select> 

If you regularly do such things, it is much more complicated in the function, or you can even create a helper class of the class.

The basic selection function is used here:

 <?php function form_select($name, $options, $selected) { $html = sprintf('<select name="%s">', $name); foreach($options as $key => $value) { $html .= sprintf('<option value="%s"', $key); if ($selected == $key) $html .= ' selected="selected"'; $html .= sprintf('>%s</option>', $value); } $html .= '</select>'; return $html; } 

Then you can create any selection just by calling:

 echo form_select('myselect', $options, $selected); 

You can easily force a function to handle additional attributes such as style, class, and identifier.

+1
source share
 <input type="radio" name="xxxx" <?php if ($xxx == 'VALUE') echo "checked=\"checked\""; ?>" /> 

similar to options in select

0
source share

All Articles