在不同的HTML下拉列表选项上显示数据库值

时间:2016-12-09 13:27:46

标签: javascript php jquery html

我有一个下拉列表,该列表使用数据库中的表中的数据导入。根据所选内容,我想显示一个表格,该表格显示与下拉列表中选择的数字相关的必要信息。因此,例如,如果我在下拉列表中选择MR_ID为1,我希望Supp_ID值(可以超过1个值)显示在表中。我怎么能这样做?

该表只有2列,MR_ID(显示在下拉列表中)和Supp_ID。

以下是我用于foreach循环的查询,我到目前为止的HTML / PHP,后面跟着一点点JavaScript

$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT DISTINCT CAST(MR_ID AS INT) AS MR_ID FROM Table_Name";
$sql_one = "SELECT CAST(Supp_ID AS INT) AS Supp_ID FROM Table_Name";

$users = $dbh->query($sql);
$users_one = $dbh->query($sql_one);

HTML / PHP:

    <!-- Dropdown List -->
    <select name="master_dropdown" id="mr_id" onChange="updatetable(this.form);">
    <option selected value="select">Choose a MR_ID</option>
        <?php foreach($users->fetchAll() as $user) { ?>
            <option data-name="<?php echo $user['MR_ID'];?>">
                <?php echo $user['MR_ID'];?>
            </option>
        <?php } ?>
    </select>
</form>

<!-- Table -->
<p> 
    <div id="table_div">
        <table border="1" id="index_table" class="ui-widget ui-widget-content">
            <thead>
                <tr class="ui-widget-header">
                <td>MR ID</td>
                <td>Supplier ID</td>
                <td>Edit</td>
                </tr>
            </thead>
            <?php foreach($users_one->fetchAll() as $supp) { ?>
            <tr>
                <td class="mr_id"><div id="dropdown_selection"></div></td>
                <td class="supp_id"><?php echo $supp['Supp_ID']?></td>
                <td><input type="button" class="edit" name="edit" value="Edit">
            </tr>
            <?php } ?>
        </table>
    </div>

此JavaScript代码读取下拉列表中选择的内容,但这是它的作用范围。

function updatetable(myForm) {

    var selIndex = myForm.master_dropdown.selectedIndex;
    var selName = myForm.master_dropdown.options[selIndex].text;
    document.getElementById("dropdown_selection").innerHTML = String(selName);
}

1 个答案:

答案 0 :(得分:1)

ajax应该是这样的:

$.ajax ({
    url: "table_drawing.php",
    method: "get", //can be post or get, up to you
    data: {
        mr_id : mr_id    
    },
    beforeSend: function () {
        //Might want to delete table and put a loading screen, otherwise ignore this
        // $("#table_div").html(loading_screen);
    },
    success: function(data){
        $("#table_div").html(data); // table_div is the div you're going to put the table into, and 'data' is the table itself.
    }
});

在table_drawing.php中,您将根据mr_id的输入绘制表格。

相关问题