javascript - 如何使用 jQuery 数据表使用 onChange 事件从 html 选择标签选项值中获取值?

标签 javascript php jquery ajax

我正在研究 jQuery 数据表以从 mysql 数据库加载少量数据。

这是 html 代码:

<table id="employee-grid"  cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
    <thead>
        <tr>
            <th>#</th>
            <th>User Id</th>
            <th>Address</th>
            <th>Package Name</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
    </thead>
</table>

从 php 页面我加载如下数据:

// skipping more code...

$nestedData[] = "
<select class='form-control changeStatus' name='status'>
    <option value=''>--Select--</option>
    <option value='1|$client_id' $statusMsg1>Active</option>
    <option value='2|$client_id' $statusMsg2>Blocked</option>
</select>";

现在加载的数据如下所示:

enter image description here

现在我想在 html selected 选项值更改时调用 Ajax 请求。它通过以下代码成功调用 Ajax 请求。

jQuery 数据表和我的 Ajax 请求的 jQuery 代码:

$(document).ready(function() {

    var dataTable = $('#employee-grid').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax":{
            url :"server_processing.php", // json datasource
            type: "post",  // method  , by default get
            error: function(){  // error handling
                $(".employee-grid-error").html("");
                $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                $("#employee-grid_processing").css("display","none");

            }
        }
    } );

    $("#employee-grid").on('change', function() {
        var status = $('.changeStatus').val();
        alert(status);
        $.ajax({
            url : "<?php echo SITE_URL . 'toplevel/update-data'; ?>",
            data : {
                'statusChange' : status
            }, 
            type : 'POST',
        });
    });

});

但是当我选择该选项时,每次它都会传递第一个选项值

例如此selected选项标记具有以下值:

<option value='1|11' $statusMsg1>Active</option>
<option value='2|11' $statusMsg2>Blocked</option>

它总是传递 1|11 值!它应该传递我选择的选项值。我不明白为什么会这样:(

注意:我认为使用 jQuery 数据表自定义 jquery 代码应该以不同的方式使用。

最佳答案

大家好,

我已经解决了。我需要使用类似的东西:

$('#employee-grid').on('change', '.changeStatus', function(){
    // testing.....
    var status = $('.changeStatus').val();
    alert(status);
}); 

解决方案是通过提供目标元素的选择器作为 on() 调用中的第二个参数来使用事件委托(delegate)。

关于javascript - 如何使用 jQuery 数据表使用 onChange 事件从 html 选择标签选项值中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657766/

相关文章:

javascript - 滚动到元素在 <ol> 中的位置

javascript - fs Node 模块的readFileSync是如何工作的?

javascript - SpreadsheetApp.openById 未通过 Google 电子表格

javascript - 在 GWT 中使用 jQuery 工具——有没有办法允许交换?

php - 如何在 PHP 中将 hmacsha1 key 设置为十六进制?

php - 如何在 php 数组中搜索 mysql 表中的所有项目?

php - 如何从数组中随机选择项目?

javascript - 使用 jQuery 或 JavaScript 从 anchor 的 href 中提取 javascript

javascript - JQuery 数据表响应扩展 : column class not retained for cells in expanded rows

javascript - 如果至少一个字段已填充值/或选定的下拉列表,则启用提交按钮