简体   繁体   中英

Jquery to populate <table> based on <select>

So I've got a form with a drop down at the top that is populated with values from a mysql table. Basically this form is to allow the addition of players to a team.

    $seasonid = $_SESSION['SEASON_ID'];
$sql="SELECT TEAM_ID, TEAM_NAME FROM TEAMS WHERE SEASON_ID=$seasonid";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
        $tid=$row["TEAM_ID"];
        $tname=$row["TEAM_NAME"];
    $options.="<OPTION VALUE=\"$tid\">".$tname;
}

What I'd like to do is when a team is selected from the list the database is queried with the TEAM_ID and all the players from that team are shown in a list below the form so that the person populating the form can see who is already on the team they've selected.

HTML

<select id = 'teamSelect'>....options....</select>
<div id = 'tableContainer'></div>

Javascript

$(function() {
    $("#teamSelect").bind("change", function() {
        $.ajax({
            type: "GET", 
            url: "path/to/server/script.php",
            data: "tid="+$("#teamSelect").val(),
            success: function(html) {
                $("#tableContainer").html(html);
            }
        });
    });

});

The javascript code will perform an ajax request to a server side php script (in the code it is the path/to/server/script.php ) This script will query your database and simply output the table as you would like it. The team that is selected will be in the $_GET variable 'tid'.

What you need to do is :

1) attach a change handler to the dropdown using jQuery (http://api.jquery.com/change/)

2) use $.get() (http://api.jquery.com/jQuery.get/) to make an async call to the server to query the database

3) return the data (either as html directly or as a JSON See http://api.jquery.com/jQuery.getJSON/)

4) in your $.get(), success handler either :
      push the resultant html into a container element on the form (see http://api.jquery.com/html/), eg a <div> <ul> or <table> depending on what you returned from the server

or    parse the JSON and generate the html before rendering it into the form.

You could use the tmpl plugin to format the html if you feel brave. http://api.jquery.com/jquery.tmpl/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM