How to retain the value of dropdown list and checkboxes of a form

11 views
Skip to first unread message

Da-Omiete Iboroma

unread,
Aug 26, 2015, 4:50:54 PM8/26/15
to Professional PHP Developers, Robert Gonzalez, Ovidiu Alexa
Hello Everybody,

Please I am finding it difficult retaining the value of the select option and checkboxes when the information a user enters does not meet the validation. 

How to retain the value of dropdown list and checkboxes in my form?

<form class=\"form-horizontal\" method=\"post\" action=\"$PHP_SELF\" enctype=\"multipart/form-data\">
 <div class=\"form-group\">
               <label for=\"conference\" class=\"col-sm-3 control-label\">Conference</label>
                <div class=\"col-sm-9\">
                 <select class=\"form-control\" name=\"conference\" value=\"$_POST[conference]\">
                     <option>--- Select Conference ---</option>
                     <option>Marketing</option>
                    <option>Public Speaking</option>
                    <option>Construction</option>
                 </select>
                </div>
              </div>
<div class=\"form-group\">
               <label for=\"tech\" class=\"col-sm-3 control-label\">Technology Needs</label>
                <div class=\"col-sm-9\">
                     $display_technology_block
                </div>
              </div>

</form>

Please not where;

$display_technology_block .= "
<input type=\"checkbox\" value=\"$_POST[technology_display]\" name=\"tech[]\"> $_POST[technology_display]&nbsp;
";

Please assist.

Thanks
Damelinks

Robert Gonzalez

unread,
Aug 26, 2015, 5:02:10 PM8/26/15
to Da-Omiete Iboroma, Professional PHP Developers, Ovidiu Alexa
dropdown lists do not use a "value" attribute, they use <option> elements with value attributes and a selected state. To default a selection in a dropdown you simply have to add a 'selected' attribute to the option element you want selected.
<select name="my_dropdown_list" id="my_dropdown_list">
    <option value="0">-- No Value --</option>
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3" selected="selected">Third</option>
    <option value="4">Fourth</option>
</select>

As far as checkboxes go, you use the "checked" attribute to default its checked state, like this:
<input type="checkbox" name="my_checkbox" checked="checked" />

Now when coupling this with your server side code, you just need to use the right conditional logic to get your markup to look like this. I would highly recommend NOT using your superglobal vars directly in your views like that. But I am sure you're only doing that for testing and development at the moment.

--

Robert Gonzalez
   
Reply all
Reply to author
Forward
0 new messages