这是我的代码。我是 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/