我正在制作一个管理面板。当用户将数据输入文本字段时,我想将文本字段中的数据复制到另一个文本字段。 我的问题是代码工作,直到我添加插入数据库功能到同一个按钮。 如何让按钮执行这两个功能。是否有更好的方法来执行onclick功能。因为我使用两个文本字段,但我真的想要一个成为产品标题。如下图所示:
代码是
<?php
$add_product_errors = array();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// price validate - must be decimal(float)
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
$add_product_errors['price'] = "Please enter a product price";
}
// item name validate
if (empty($_POST['item_name'])) {
$add_product_errors['item_name'] = "Please enter a name";
}
// item name description
if (empty($_POST['desc'])) {
$add_product_errors['desc'] = "Please enter a product description";
}
//add to database
//if (empty($add_product_errors)) {
$q = 'INSERT INTO Product (Product_Name,Product_Desc,Product_Price) VALUES (?,?,?)';
$stmt = mysqli_prepare($dbc, $q);
//debugging
$stmt = mysqli_prepare($dbc, $q) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $item_name, $desc, $price);
$item_name = strip_tags($_POST['item_name']);
$desc = strip_tags($_POST['desc']);
//100 - changes the way the decimal displays in database
$price = strip_tags($_POST['price'] * 100);
//execute the query
mysqli_stmt_execute($stmt);
printf("%d Item Added.\ ", mysqli_stmt_affected_rows($stmt) === 1); {
mysqli_stmt_close($stmt);
}
}
?>
HTML
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" >
<input type="textfield" id="title" name="title" value="">
<input type="textfield" id="item_name" name="item_name" placeholder="item name" value="" <?php $add_product_errors ?>/><br>
<textarea id="desc" name="desc" value="" placeholder="Item description" rows="3" maxlength="200" required ><?php $add_product_errors ?></textarea><br>
<input type="textfield" id="price" name="price" value="" placeholder="£" maxlength="30" required <?php $add_product_errors ?>/><br>
<input type="submit" name="add" value="add" value="add" class="btn" onclick="myFunction()">
<!-- copy item_name to page title -->
<script>
function myFunction() {
document.getElementById("title").value = document.getElementById("item_name").value;
}
</script>
答案 0 :(得分:1)
考虑将提交输入更改为常规按钮,以便您可以完全控制控制流。它也可能使控制流更清晰,让您理解。
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">
... your HTML here ...
<input type="button" name="add" value="add" value="add" class="btn" onclick="myFunction()">
</form>
<script>
function myFunction() {
// Update your field value
document.getElementById("title").value = document.getElementById("item_name").value;
// Submit your form.
document.forms["product_form"].submit();
}
</script>
答案 1 :(得分:0)
您可以在onsubmit事件上绑定文本的复制,如下所示:
<form name="product_form" enctype="multipart/form-data" action="admin_p.php" method="post" accept-charset="utf-8" onsubmit="myFunction()">