【问题标题】:How can I prefill my form based on a dropdown menu selection value?如何根据下拉菜单选择值预填表单?
【发布时间】:2015-04-05 03:28:07
【问题描述】:

我有一个表单,它有一个下拉选择菜单,可以从我的数据库中加载发票 ID。我正在尝试根据从下拉菜单中选择的发票价值预先填写我的表格。在我的数据库中有一个列“invoiceidcopy”,其中包含一个值,该值显示为我的下拉菜单的选择。如果您在下面我的数据库表的图像中注意到您会注意到第一行/记录的 invoiceidcopy 字段是空白的……在我的下拉菜单中……当然……第一个选择是空白的。最终,我下面的代码试图预填我的表单,只有当我从下拉菜单中选择空白选项而不是其他 2 个选项时才有效?如何根据下拉菜单选择值预填表单?

表格

<form action="#">

<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>

<button id="submit-id">Prefill Form</button>

<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">



<button id="submit-form" name="Submit-form" type="submit">Submit</button>


</form> 

脚本

<script>
     $(function(){


        $('#submit-id').on('click', function(e){  


            var invoiceidcopy = $('#dropdown-select').val();
            e.preventDefault(); 

             $.ajax({
              url: "/tst/orders2.php",
              data: {
                invoiceidcopy: invoiceidcopy
              }
            }).done(function(data) {

    data = JSON.parse(data);

$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);


});
        });
     });
</script>

/tst/orders2.php

<?php

// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");


// Check if the connection failed
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  die();
}

   if (isset($_GET['invoiceidcopy']))
{
    $invoiceidcopy= $_GET['invoiceidcopy'];

   $query = "SELECT txt1, txt2, q1
        FROM seguin_orders
  WHERE invoiceidcopy = '".($invoiceidcopy)."'";

    $result = mysqli_query($con,$query);

    while ($row = mysqli_fetch_assoc($result)) 
        {
 echo json_encode($row);
 die(); 
    }
}
?>

【问题讨论】:

    标签: javascript php jquery html mysql


    【解决方案1】:

    您的错误来源似乎来自您通过 ajax 发送到 php 的 json 数据。您应该尝试将 data 键括在引号中,以便 javascript 不会将其替换为变量值。

       data: {
           'invoiceidcopy': invoiceidcopy
       }
    

    另一个可能的错误来源是从表中选择记录的 sql。 您是否尝试过像这样从变量名中删除括号

     $query = "SELECT txt1, txt2, q1
            FROM seguin_orders
      WHERE invoiceidcopy = '".$invoiceidcopy."'";
    

    甚至使用大括号

     $query = "SELECT txt1, txt2, q1
            FROM seguin_orders
      WHERE invoiceidcopy = {$invoiceidcopy}";
    

    此外,最好在将值发送到 php 之前检查它,以确保它是您所期望的。例如,您可以执行以下操作:

     e.preventDefault();
        var invoiceidcopy = $('#dropdown-select').val();
        alert(invoiceidcopy); /*display the value to confirm it is correct */
        // use the javascript console
        console.log(invoiceidcopy);
    

    【讨论】:

    • 好的。如果您最终找到解决方案,请务必提供有关解决方案的反馈。
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2017-08-03
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多