Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * function to create a html select box and set the selected value if the item is found in post
- *
- * @param string $elementId and id of html element
- * @param array $options of items to add to select box value => display text
- * @param string $attributes of attributes to add e.g class=''
- * @return string
- */
- function createSelectHtml($elementId, $options, $attributes=''){
- $returnHtml="";
- //start building return html
- $returnHtml.="\n<select name='{$elementId}' id='{$elementId}'>\n";
- //default selected item to blank (if not found defaults to 1st item)
- $selectedValue='';
- //check if a post has been sent containing this item
- if ($_POST && isset($_POST[$elementId])){
- //a post has been done set selected to post value
- $selectedValue=$_POST[$elementId];
- }
- //loop through options adding to html
- foreach ($options as $id => $value){
- //check if the item we are adding is the selected item
- if ($id==$selectedValue){
- $isSelected=" selected='selected'";
- }else{
- $isSelected="";
- }
- //add this option to the return Html
- $returnHtml.= " <option value='{$id}'{$isSelected}>{$value}</option>\n";
- }
- //end select box
- $returnHtml.= "</select>\n";
- //if the item has been submitted check if it is valid
- if ($_POST){
- //display error message
- if (!selectIsValid($elementId, $options)){
- $returnHtml.= "<span class='error'>Please select a valid option from the list provided.</span>\n";
- }
- }
- //return html
- return $returnHtml;
- }
- /**
- * function to check if a valid option has been posted to a form
- *
- * @param string $elementId and id of html element
- * @param array $options of items to add to select box value => display text
- * @return boolean
- */
- function selectIsValid($elementId, $options){
- $isValid=false;
- //loop through options adding to html
- foreach ($options as $id => $value){
- if ($id!='' && $id==$_POST[$elementId]){
- $isValid=true;
- }
- }
- return $isValid;
- }
- <form method="post">
- <?php
- $validOptions=array('' => 'Please select', 1 => 'Matt', 2 => 'John', 3 => 'Smith');
- echo "<label>Please select:</label>" . createSelectHtml('aSelectBox', $validOptions) . "";
- echo "<p> </p>";
- echo "<label>Please select:</label>" . createSelectHtml('aSelectBox1', $validOptions) . "";
- echo "<p> </p>";
- if ($_POST){
- if(selectIsValid('aSelectBox', $validOptions)){
- echo "<p>The form is valid</p>";
- }
- }
- ?>
- <input type="submit">
- </form>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement