views:

32

answers:

0

So here is the deal, I have a form that appears in a table. Each row has a certain amount of information, one of the form elements in a "select" dropdown box. This "select" contains various categories as optgroups and the information under those categories are the options. This is quickly becoming unmanageable as the list gets longer and longer.

User can add or remove rows as they see fit (so that as many rows can be submitted as user wants) via a nice little onclick that fires off a JS function that appends a row of blank form elements to the table.

I would like to figure out how to customize the "select" box so that user can pick a category in one box, and then the associated information in another.

I found a jquery script that handles autopopulating selects here (http://www.codingcereal.com/2009/09/autopopulate-select-dropdown-box-using-jquery/), but I'm not sure how to best customize this script so that I can use it multiple times. The JS and associated PHP from the tutorial appear below...

    <script type="text/javascript">
  $(document).ready(function(){
    $("#selectionresult").hide();

    $("#selection").change( function() {
        $("#selectionresult").hide();
        $("#result").html('Retrieving ...');
        $.ajax({
            type: "POST",
            data: "data=" + $(this).val(),
            url: "demo/jquery-autopopulate-select-dropdown-box-response.php",
            success: function(msg){
                if (msg != ''){
                    $("#selectionresult").html(msg).show();
                    $("#result").html('');
                }
                else{
                    $("#result").html('<em>No item result</em>');
                }
            }
        });
    });
});
</script>

<?PHP
$expectedValues = array("food", "animals", "flowers");

$selectionArr['food'] = array('pizza', 'spaghetti', 'rice');
$selectionArr['animals'] = array('cat', 'dog', 'girrafe', 'pig', 'chicken');
$selectionArr['flowers'] = array('rose', 'sampaguita');

if (isset($_POST['data']) and in_array($_POST['data'], $expectedValues)){
    $selectedArr = $selectionArr[$_POST['data']];

    foreach($selectedArr as $optionValue){
        echo '<option>' . $optionValue . '</option>';
    }
}
?>

My knowledge of jquery and javascript in general is lacking. How can I make multiple instances of this box that are created whenever I create a new row (via JS)?

Thanks everyone!