选择一个选项后自动显示数据库值

时间:2016-07-08 08:58:39

标签: javascript php

假设我有这样的SQLite数据库:

+----+-----------+-------+
| id | name      | price |
+----+-----------+-------+
| C1 | Car       | 50000 |
| B1 | Bike      | 1500  |
| M1 | Motorbike | 15000 |
| T1 | Truck     | 99000 |
+----+-----------+-------+

然后将数据库显示到选择表单我使用此代码:

<form method="post" action="action.php">
    <table>
        <tr>
            <td>Vehicle</td>
            <td>:</td>
            <td>                            
                <select name='id_vh' onchange='OnChange(this.value)' required>
                <option selected value=''>choose</option>
                    <?php               
                        $sql="SELECT * FROM vehicle ORDER BY name ASC";
                        $result=$db->query($sql);
                        $row=$result->fetchall(PDO::FETCH_ASSOC);
                        foreach($row as $dt){
                        echo "<option value='$dt[id]'>$dt[name]</option>";}
                    ?>
                </select>
            </td>
        </tr>

如何在选择选项后自动显示价格,我使用这样的代码但不起作用:

<tr>
            <td>Price</td>
            <td>:</td>
            <?php
            if(isset($_POST['id_vh'])){
                $idv=$_POST['id_vh'];
                $query=$db->prepare("SELECT * FROM price WHERE id = '$idv'");
                $query->execute();
                $result    =   $query->fetch(PDO::FETCH_ASSOC);
                echo"<td>$result[price]</td>";
            }
            ?>
         </tr>
    </table>
</form>

1 个答案:

答案 0 :(得分:0)

设置要处理的表单的ID

<form id="vehicleForm" method="post" action="action.php">
  <table>
    <tr>
      <td>Vehicle</td>
      <td>:</td>
      <td>                            

将Id设置为您的选择器以处理

<select id='id_vh' name='id_vh' required>
  <option selected value=''>choose</option>
  <?php               
     $sql="SELECT * FROM vehicle ORDER BY name ASC";
                    $result=$db->query($sql);
                    $row=$result->fetchall(PDO::FETCH_ASSOC);
                    foreach($row as $dt){
                    echo "<option value='$dt[id]'>$dt[name]</option>";}
 ?>
            </select>
        </td>
    </tr>

添加jquery文件

<script type="text/javascript" src="/js/jquery.min.js"></script>

添加拦截更改的功能

<script Type="text/javascript">
  $('#id_vh').on("change",(function (e) {
    /*just for debugging*/  
    alert( this.selectedOptions[0].value);
    /*submit the Form*/ 
    vehicleForm.submit();
}));
</script>  

那应该有用。 $ _POST现在将包含id_vh

的值