获取文本框中所有选定复选框的值

get the value of all selected checkboxes in textbox

本文关键字:复选框 取文本 获取      更新时间:2023-09-26

我正在尝试创建一个带有某个值的复选框,然后显示用逗号分隔的选定复选框的值。

我可以创建一个复选框,但无法在文本框中显示值。请帮忙。

http://jsfiddle.net/0q0ns1ez/1/

function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB[0] = $(this).attr("id");
            }
        });
        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    

您的方法的主要问题在于这一行:

CountSelectedCB[0] = $(this).attr("id");

使用数组的方式 CountSelectedCB ,您总是在第一个位置(索引 0(插入复选框的 id,因此,如果没有选中复选框,无论选中多少复选框(或没有 id(,您都将始终得到一个 id。

您应该将上面的行更改为:

CountSelectedCB.push($(this).attr("id"));

此外,由于CountSelectedCB的作用域比函数displayCheckbox更高,因此它在调用displayCheckbox之间保留其值,因此在每次触发change事件时,您必须在添加更新的检查 ID 列表之前清除数组。否则,更新后的 ID 列表将附加到以前存储的列表中。

以下是您的代码的外观(示例小提琴(:

function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        CountSelectedCB.length = 0;                       // clear selected cb count before adding the updated ones
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("id")); // add id to count selected cb
            }
        });
        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    

$(document).ready(displayCheckbox);
CountSelectedCB = [];
function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        
        CountSelectedCB.length = 0; // clear selected cb count
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("id"));
            }
        });
        
        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb1">Checkbox #1
<input type="checkbox" id="cb2">Checkbox #2
<input type="checkbox" id="cb3">Checkbox #3
<hr />
<input name="selectedCB">

这是实现此目的的另一种方法(示例小提琴(

实质上,您最初将change侦听器添加到将打印所有复选框的每个复选框(在文档就绪或某个其他事件上,具体取决于您的应用程序逻辑(。

var checkboxes = $("input:checkbox"); // save checkboxes into a variable so we don't waste time by looking them up each time
// add change listeners to checkboxes
$.each(checkboxes, function() {
  $(this).change(printChecked);
})

然后你做了一个函数来实际打印复选框的 ID:

function printChecked() {
    var checkedIds = [];
    // for each checked checkbox, add it's id to the array of checked ids
    checkboxes.each(function() {   
        if($(this).is(':checked')) {
            checkedIds.push($(this).attr('id'));
        }
    });
    $('input[name=selectedCB]').val(checkedIds); 
}

$(document).ready(displayCheckbox);
function displayCheckbox() {    
   
    var checkboxes = $("input[type=checkbox]");
    var displayField = $('input[name=selectedCB]');
    $.each(checkboxes, function() {
      $(this).change(printChecked);
    })
    
    function printChecked() {
        var checkedIds = [];
        // for each checked checkbox, add it's id to the array of checked ids
        checkboxes.each(function() {   
            if($(this).is(':checked')) {
                checkedIds.push($(this).attr('id'));
            }
        });
        displayField.val(checkedIds); 
    }
}  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb1">Checkbox #1
<input type="checkbox" id="cb2">Checkbox #2
<input type="checkbox" id="cb3">Checkbox #3
<hr />
<input name="selectedCB">

您正在覆盖CountSelectedCB[0]

最好尝试类似的东西

var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
    $target.val(
        $checkboxes.map(function() {
            return this.checked ? this.id : null;
        }).get().join()
    );
});

var abc = [1, 2, 3];
var CountSelectedCB = new Array();
var s1 = document.getElementById('demo');
for (var option in abc) {
  if (abc.hasOwnProperty(option) && !document.getElementById('CheckBox' + abc[option])) {
    var pair = abc[option];
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = 'CheckBox' + pair;
    checkbox.name = pair;
    checkbox.value = pair;
    s1.appendChild(checkbox);
    var label = document.createElement('label')
    label.htmlFor = pair;
    label.appendChild(document.createTextNode(pair));
    s1.appendChild(label);
    s1.appendChild(document.createElement("br"));
  }
}
var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
  $target.val(
    $checkboxes.map(function() {
      return this.checked ? this.id : null;
    }).get().join()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="demo"></div>
<input type="text" name="selectedCB" />

或者像这样:

var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
    $target.val(
        $checkboxes.filter(':checked').map(function() {
            return this.id;
        }).get().join()
    );
});

var abc = [1, 2, 3];
var CountSelectedCB = new Array();
var s1 = document.getElementById('demo');
for (var option in abc) {
  if (abc.hasOwnProperty(option) && !document.getElementById('CheckBox' + abc[option])) {
    var pair = abc[option];
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = 'CheckBox' + pair;
    checkbox.name = pair;
    checkbox.value = pair;
    s1.appendChild(checkbox);
    var label = document.createElement('label')
    label.htmlFor = pair;
    label.appendChild(document.createTextNode(pair));
    s1.appendChild(label);
    s1.appendChild(document.createElement("br"));
  }
}
var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
  $target.val(
    $checkboxes.filter(':checked').map(function() {
      return this.id;
    }).get().join()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="demo"></div>
<input type="text" name="selectedCB" />

您遍历所有复选框并将值保存在某个字符串中,然后将其放在文本字段中:

var string = "";
$('.checkButtonClass').each(function() {
     if($(this).is(':checked')) {
     string = string + $(this).val() +", ";
}
$("#idTextfield").html(string);