填充文本框与组合框选择使用php javascript

Populating textbox with combobox selection using php javascript.

本文关键字:php javascript 组合 文本 填充 选择      更新时间:2023-09-26

我有html表单填充数据从数据库。第一个是组合框,第二个是文本框。

我的问题是如何通过选择组合框来填充文本框。我已经尝试过使用javascript,但它没有工作,请看看我的代码。

//这是HTML表单:当我在combobox上选择nama_brg时,它将在tb_baranga中搜索harga,其中nama = nama_brg

echo '<tr>';
    echo '<td width=100px>Nama Barang</td>';
    echo '<td>:</td>';
    echo '<td>';
    echo    '<select name="nama_brg" onchange="ambilharga()">
                <option value="kosong">PILIH</option>';
                $getbrg = "select * from tb_baranga";
                $query2 = mysql_query($getbrg);
                while ($row2=mysql_fetch_array($query2))
                {
                    echo '<option value="'.$row2['nama'].'">'.$row2['nama'].'</option>';
                }
            echo '</select>';
    echo '</td>';
    echo '</tr>';

//这是我的javascript

<script type="text/JavaScript">
         function ambilharga()
         {
         <?php
         $cekbrg = "select * from tb_baranga";
         $hasil = mysql_query($cekbrg);
         while ($row5 = mysql_fetch_array($hasil))
         {
           $namabrg = $row5['nama'];
           echo "if (document.add_invoice.nama_brg.value == '".$namabrg."')";
           echo "{";
           $gethrg = "select harga from tb_baranga where nama='".$namabrg."'";
           $hasil2 = mysql_query($gethrg);
           while ($data2 = mysql_fetch_array($hasil2))
           {
               $price = $data2['harga'];
               echo "document.getElementById('harga2').innerHTML = '".$price."' ";
                echo "document.getElementById('harga2').value = '".$price."' ";
           }

           echo "}";
         }
         ?>
         }
    </script>

这是我的表结构

tb_baranga
nama varchar 30
harga int

试试这个:

按照我下面提到的步骤做。

>> Check all values are coming proper in drop-down box.
>> Call jquery ajax on change of dd box. (Ref. https://api.jquery.com/jQuery.ajax/)
>> Show the value you get in ajax to text-box.