Alex Electronics

PHP List Box


This is a simple bit of JavaScript code that allows PHP to read the complete contents of a list box.


Introduction

When a list box is returned in an HTTP PUT, the only thing PHP can read is the first selected item in the list box. This is very irritating if you need to read all of the items in a list box with PHP. There is a very simple solution, although a little crude, which uses JavaScript on the client side to select the entire list box when the form is submitted.

Code

Here is a simplified listing of the code directly involved with this tool:

function selectAll(list) {
    var i;
    i = 0;
    list.multiple = true;
    do {
    list[i].selected = true;
    } while (i++ < list.length);
}

Here is the (simplified) definiton of the form and list in this example:

<form name="sampleList" method="POST" action="<?PHP echo $_SERVER['PHP_SELF']?>">
    <select name="list[]" id="list" size="5">
        <option value="Option1">Option1</option>
        <option value="Option2">Option2</option>
        <option value="Option3">Option3</option>
    </select>
    <input type="submit" value="submit" />
</form>

Here is the PHP code involved:

<?PHP
if (count($_POST) > 0 && array_key_exists("lst", $_POST)) {
    echo "<br />\r\nList:<br/>\r\n";
    $list = $_POST['lst'];
    for ($i = 0; $i < count($list); $i++ ) {
        echo $list[$i] . "<br />\r\n";
    }
}
?>