从表中的动态下拉列表中获取选定的值 [英] Get selected value from dynamic dropdown in table

查看:72
本文介绍了从表中的动态下拉列表中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,可以向表中添加一行,以便可以插入数据. <td>标记之一填充一个下拉菜单.我需要从该下拉列表中获取值,然后在ajax调用中发布回php页面,以将数据插入数据库中.我尝试过的所有内容均未返回position_ID的定义.

I have a button that adds a row to a table so that data can be inserted. One of the <td> tags populates a dropdown menu. I need to get the value from that dropdown to post in an ajax call back to a php page to insert the data in the database. Everything I've tried has returned undefined for position_ID.

我在POST上收到500错误,我认为这是由于在插入功能中未设置var position_ID = $(this).parents('tr').find('.positionList').val();造成的.

I'm getting a 500 Error on the POST and I think it's due to var position_ID = $(this).parents('tr').find('.positionList').val();, in the Insert function, not being set.

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");
       }
     });

推荐答案

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

还请注意,@ Kaka Sarmah是正确的.即使这样也不起作用,因为您正在创建具有相同ID的多个元素. ID必须是唯一的.尝试改为给它一个类.

Also note that @Kaka Sarmah is correct. Even this will not work because you're creating multiple elements with the same ID. IDs must be unique. Try giving it a class instead.

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

然后在您的JavaScript中,您可以尝试使用该类找到它.像这样:

Then in your javascript you can try to locate it using that class. Something like:

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

这篇关于从表中的动态下拉列表中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆