当用户从下拉列表中选择值时,如何在文本字段中显示数据库值

时间:2013-09-13 15:26:17

标签: javascript php select drop-down-menu textfield

当用户选择下拉列表值时,价格将根据数据库显示。我正在考虑代码。我希望有人可以帮助我。

<form action="next.php" method="post">

<center>

<table>

droplist,用于显示表tabelmedicine

中的数据库行名
<tr><td width="116">Medicine name</td><td width="221">

<center>:

<select name="name" id="name">

<option>--- Choose Medicine ---</option>

与db

连接
<?php

mysql_connect("localhost", "root", "");

mysql_select_db("arie");


$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");

if(mysql_num_rows($sql) != 0){

while($row = mysql_fetch_assoc($sql)){

echo '<option>'.$row['name'].'</option>';


}

}

?>

</select ></center>

</p></td></tr>

textfield显示tabelmedicine row priceperunit的价格值

<tr><td><p>Price</p></td><td><p align="center">:<input type="text" name="price" 

id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">

</p></td></tr>


<script>

var select = document.getElementById('name');

var input = document.getElementById('price');

select.onchange = function()

{

    input.value = select.value;

}

</script>

1 个答案:

答案 0 :(得分:1)

这应该这样做。只需确保$row['price']是正确的数据库字段密钥

<form action="insertout.php" method="post">
<center>
<table>
<tr>
    <td width="116">Medicine name</td>
    <td width="221">
        <center>
            :
            <select name="name" id="name">
                <option>--- Choose Medicine ---</option>
                <?php
                    mysql_connect("localhost", "root", "");
                    mysql_select_db("arie");
                    $sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
                    if(mysql_num_rows($sql) != 0){
                        while($row = mysql_fetch_assoc($sql)){
                            echo '<option value="'.$row['price'].'">'.$row['name'].'</option>';
                        }
                    }
                ?>
            </select >
        </center>
        </p>
    </td>
</tr>
<tr>
    <td>
        <p>Price</p>
    </td>
    <td>
        <p align="center">:<input type="text" name="price" 
            id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
        </p>
    </td>
</tr>
<script>
    var select = document.getElementById('name');
    var input = document.getElementById('price');
    select.onchange = function(){
        input.value = select.value;
    }
</script>