Jquery to populate <table> based on <select>

流过昼夜 提交于 2019-12-08 07:26:58

问题


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.


回答1:


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'.




回答2:


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/



来源:https://stackoverflow.com/questions/5704180/jquery-to-populate-table-based-on-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!