Search code examples
phpjquerymysqlhtml-select

Hide option in a select box dependant on previous choices. Options generated from SQL


I would like my user to be able to select the people they went hiking with. I have used JScript that allows the user to add more Selection boxes depending on how many people were on the hike. The names in this selection box are generated from a database query.

I would like to put something in place that would stop the same person being selected multiple times from different selection boxes. For example if option 1 in selected in the first section box, it should not be available to the user in the 2nd, 3rd, 4th.....selection box.

The selection boxes are generated using the following code

<TABLE id="buddyTable" class="form" border="1">
            <TR>
                <td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
                <TD><label>Buddy</label>
                <select name="buddy[]">
                    <option>Solo</option>
                <?php

            if ($result->num_rows > 0) {
                // output data of each row
                while($row = $result->fetch_assoc()) {
                echo '<option value = "'.$row["idPerson"].'">'.$row["Forename"]. ' '.$row["Surname"].'</option>';
                //echo "name: " .$row["Forename"]. " " . $row["Surname"]. "<br>";
                }
            } 
            else {
                echo "0 results";
            }               
            $conn->close();
            ?>
                </select>
                </TD>
            </TR>
            </TABLE>

The JScript to allow more selection boxes to be added is here

function addRowBuddy(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 10){                          // limit the user from creating fields more than your limits
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
    for(var i=0; i<colCount; i++) {
        var newcell = row.insertCell(i);
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
    }
}else{
     alert("Maximum number of buddies is 10.");

}

}

I have looked for a few solutions and although they are good, none of them inform me on how to do this when MySQL/php is also involved.

Any hints, suggestions or guides would be greatly appreciated.


Solution

  • If you don't mind using a framework, you could use w2ui's enum field (Multi Select):

    http://w2ui.com/web/docs/form/fields-enum

    The items array for the field can be either pulled directly from an url or it can be a predefined array.

    It would also save you the hassle of creating more selection boxes as you could select all persons in one field.

    Or maybe you could use http://aehlke.github.io/tag-it/