在 JavaScript 的按钮单击事件中打印与 HTML 中的复选框关联的值

Print values associated with checkboxes in HTML on button click event of JavaScript

本文关键字:HTML 复选框 关联 打印 按钮 单击 事件 JavaScript      更新时间:2023-09-26

计划从 HTML 页面上的选择中获取特定的 ID 值(此处的选择表示复选框)。这是我的按钮单击事件的代码(按钮将获取行号或 id):

$("a", button).click(function () {
            $('#groups').find('tr').each(function () {
                 var row = $(this);
                 if (row.find('input[type="checkbox"]').is(':checked')) {
                    console.log($(this));
            }
        });
});

这将返回有关行 + tr 标签的其他信息,但是,我只想要其中的 ID 部分。这是我从上面的代码中得到的示例输出:

[tr#row-12150.row.oddSelected, context: tr#row-12150.row.oddSelected]
[tr#row-12151.row.evenSelected, context: tr#row-12151.row.evenSelected]

这意味着我已从#groups表中选择了12150 and 12151。我如何只12150 and 12151拉取行号而不是整个详细输出,我希望它存储在多个行号的数组/(JS数组)中。

你有行 根据.find('tr'),你应该能够去:

console.log($(this).attr('id')); //this should show the id in your console.

因此,您的代码变为:

$("a", button).click(function () {
            $('#groups').find('tr').each(function () {
                 var row = $(this);
                 if (row.find('input[type="checkbox"]').is(':checked')) {
                   console.log($(this).attr('id'));
            }
        });
});

然后只获取您可以使用的数字:

var number = $(this).attr(id).split('-')[1] //assuming it's always row-<<some number>>

把它们放在一起:

 $("a", button).click(function () {
                $('#groups').find('tr').each(function () {
                     var row = $(this);
                     if (row.find('input[type="checkbox"]').is(':checked')) {
                       var number = $(this).attr('id').split('-')[1] //assuming it's always row-<<some number>>;
                       console.log(number);
                }
            });
    });

将其存储在数组中:

$("a", button).click(function () {
                    var checkedRows = []; //define empty array.
                    var count = 0; //keep a counter to use for the array.
                    $('#groups').find('tr').each(function () {
                         var row = $(this);
                         if (row.find('input[type="checkbox"]').is(':checked')) {
                           var number = $(this).attr('id').split('-')[1];
                           checkedRows[count] = number; //add the number to our array.
                           count++; //increase the count
                    }
                });
        });

确保您的表单和按钮首先具有 id,然后尝试以下操作:

$('#buttonId').click(function(){
  $('#formId input:checked').each(i, e){
    console.log($(e).attr('id'));
  }
});