首页 > 解决方案 > 从表中的动态下拉列表中获取选定的值

问题描述

我有一个按钮,可以在表格中添加一行,以便可以插入数据。其中一个<td>标签填充下拉菜单。我需要从该下拉列表中获取值以在 ajax 调用中发布回 php 页面以将数据插入数据库中。我尝试过的所有东西都返回 undefined for position_ID

我在 POST 上收到 500 错误,我认为这是由于var position_ID = $(this).parents('tr').find('.positionList').val();在 Insert 函数中未设置。

HTML 代码:

<html>
    <head>
      <script src='jquery-3.4.1.js' type='text/javascript'></script>
      <script src='script.js' type='text/javascript'></script>
    </head>
    <body>
        <button type="button" name="add" id="add">Add</button>
        <table id="dataTable">
            <tr>
                <th>Last Name</th>
                <th>First Name</th>
                <th>Location Number</th>
                <th>Position</th>
            </tr>
        </table>
    </body>
</html>

PHP代码:

<?PHP>
    $sql = "SELECT positionID, name FROM position";

    $result = mysqli_query($db,$sql);

    $position_arr = array();

    while( $row = mysqli_fetch_array($result) ){
        $positionID = $row['positionID'];
        $name = $row['name'];

        $position_arr[] = array("positionID" => $positionID, "name" => $name);
    }

    // encoding array to json format

    $JSON_array = json_encode($position_arr);
    echo $JSON_array;
?>
<?PHP>
    if(isset($_POST["last_name"], $_POST["first_name"], $_POST["location_num"], $_POST["position_ID"]))
    {
         $lastName = mysqli_real_escape_string($db, $_POST["last_name"]);
         $firstName = mysqli_real_escape_string($db, $_POST["first_name"]);      
         $locationNum = mysqli_real_escape_string($db, $_POST["location_num"]);
         $positionID = mysqli_real_escape_string($db, $_POST["position_ID"]);

         $sqlInsertEmployee = "INSERT INTO employee(lastName, firstName, positionID, locationID) SELECT ?, ?, positionID, locationID from location join position p on p.positionID = ? where number = ?";
         $stmtInsertEmployee = mysqli_prepare($db,$sqlInsertEmployee);
         mysqli_stmt_bind_param($stmtInsertEmployee, "ssss", $lastName,$firstName,$positionID,$locationNum,);
         mysqli_stmt_execute($stmtInsertEmployee);
         mysqli_stmt_close($stmtInsertEmployee);
    }   
?>

脚本代码:

$('#add').click(function(){
       var html = '<tr>';
       html += '<td contenteditable id="lastName"></td>';
       html += '<td contenteditable id="firstName"></td>';
       html += '<td contenteditable id="locationNum"></td>';
       html += '<td contenteditable id="positionID"><select class="positionList"><option></option></select>';   

       $(document).ready(function() {
              var data
              $.ajax({
                dataType: 'json',
                url: 'get-position.php',
                data: data,
                success: function(data) {
                    // begin accessing JSON data here
                  console.log(data)
                  //data = jQuery.parseJSON(data);
                  var html_to_append = '';
                  html_to_append += '<option value="0">-- Select One --</option>'
                  $.each(data, function(i, item) {
                    html_to_append += '<option value="' + item.positionID + '">' + item.name + '</option>';
                  });
                  $(".positionList").html(html_to_append);
                },
              })
            })


       html += '</td><td><button type="button" name="insert" id="insert">Insert</button></td>';
       html += '</tr>';
       $('#dataTable tr:first').after(html);
    });




    $(document).on('click', '#insert', function(){
       var last_name = $('#lastName').text();
       var first_name = $('#firstName').text();    
       var location_num = $('#locationNum').text();

       var position_ID = $(this).parents('tr').find('.positionList').val();

       console.log(position_ID);

       if(first_name != '' && last_name != '' && location_num != '')
       {
        $.ajax({
         url:"insert.php",
         method:"POST",
         data:{last_name:last_name, first_name:first_name, location_num:location_num, position_ID:position_ID},
         success:function(data)
         {
          $('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
          $('#dataTable').DataTable().destroy();
          fetch_data();

         }
        });
        setInterval(function(){
         $('#alert_message').html('');
        }, 5000);
       }
       else
       {
        alert("All Fields is required");
       }
     });

标签: javascriptjqueryajax

解决方案


.val () 方法用于获取元素的值。

另请注意@Kaka Sarmah 是正确的。即使这样也行不通,因为您正在创建具有相同 ID 的多个元素。ID 必须是唯一的。试着给它上课。

html += '<td contenteditable class="positionID"><select class="positionList"><option></option></select>';

然后在您的 javascript 中,您可以尝试使用该类找到它。就像是:

var position_ID = $(this).parents('tr').find('.positionList').val();

推荐阅读