javascript - 有没有办法在 onchange 时填充其他文本框?

标签 javascript php

这是我的代码。我是 php 新手。提前抱歉。 我实际上想检查 txtbarcode 中的输入,如果它存在于我的数据库中,我想填充 txtdescription,但我不知道该怎么做,或者甚至可能吗?

        <?php
            $barcode = $_POST['txtbarcode'];
            $query = "SELECT * FROM product WHERE product_id = '$barcode'";
            $query_exe = mysql_query($query);
            $chk_query = mysql_num_rows($query_exe);

            if($chk_query > 0)
            {
            $row = mysql_fetch_assoc($query_exe);

            ?>
            <th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>"  style="width:80px"/></th>
            <th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>"    style="width:100px"/></th>
            <?php
            }
            ?>

最佳答案

您可以使用 JQuery Ajax 来完成此操作。只需使用条形码字段上的更改监听器,它就会向 check_barcode 文件发送 ajax 调用 - 这将查询表并回显您想要的数据。然后,结果将通过 JavaScript 放置到另一个文本字段中:)。

以下是一个单独的 PHP 文件。

<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------

if (isset($_POST['barcode'])) {
    $query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
    $num_rows = mysql_num_rows($query);
    if ($num_rows > 0) {
        $row = mysql_fetch_assoc($query);
        echo $row['product_name'];
    }
}
?>

以下是您的 HTML 和 JavaScript 代码。

<pre><code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $(document).ready(function() { $('#txtbarcode').change(function() { var barcode = $(this).val(); $.ajax({ url: 'check_barcode.php', type: 'POST', data: {barcode: barcode}, success: function(result) { $('#txtdescription').val(result); } }); }); }); </script> <input type="text" name="txtbarcode" id="txtbarcode" /> <input type="text" name="txtdescription" id="txtdescription" /> </code></pre>

<小时/>

更新:返回更多数据,并填充额外字段。

您需要从包含这两个值的 php 脚本中回显 json 数组。

例如:

echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));

然后在 JavaScript 中

<script>
$.ajax({
    url: 'check_barcode.php',
    type: 'POST',
    data: {barcode: barcode},
    dataType: 'json',
    success: function(result) {
        $('#txtdescription').val(result.product_name);
        $('#unitofmeasure').val(result.unit_measure);
    }
});
</script>

关于javascript - 有没有办法在 onchange 时填充其他文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898750/

相关文章:

c# - 使用 JavaScript 更改文本框的显示时 Ajax requiredFieldValidator 弹出

php - 有什么方法可以防止AJAX页面在浏览器中单独查看吗?

javascript - 如何将 this.score 传输到文本文件以获得高分列表? ( Ajax )

php - NginX 不执行 PHP

Javascript 对素数求和崩溃

javascript - Java Script DOMException Web Audio API audioContext.createMediaElementSource 再次调用该函数

javascript - 带有 jquery ui slider 的动态输入字段不起作用

javascript - AngularJS:如何更新复选框选择/取消选择上 $scope 关联数组的键?

php - 是否可以让 ajax 每微秒调用一次 php 脚本来检查文本文件是否已更改?

javascript - 如何在开发者api2.4中获取facebook好友列表