如何使用jquery从输入复选框中检索文本

How do I retrieve text from an input checkbox with jquery?

本文关键字:检索 文本 复选框 输入 何使用 jquery      更新时间:2024-04-08

我正在尝试检索所选复选框的文本,如:

HTML:

<label class="checkbox">        
    <input type="checkbox" name="priority" value="2" checked="checked">2 - Critical
</label>
<label class="checkbox">        
    <input type="checkbox" name="priority" value="3">3 - Important
</label>

jquery:

$('#priorityContents input:checkbox:checked').each(function() {
    if(priorityText.length > 0) {
        priorityText = priorityText + "|";
    }
    priorityText = priorityText + $(this).text();
});
alert(priorityText);

我希望看到:

2 - Critical

我的控制台没有任何错误。我错过了什么?

您可以尝试:

<input id="cb" type="checkbox" name="priority" value="2" checked="checked">
<label for='cb' class="checkbox"> 2 - Critical</label>

$('#priorityContents input[type="checkbox"]:checked').each(function() {
    var txt = $(this).next('label').text();
});

请注意,不推荐使用:checkbox选择器您可以使用input[type="checkbox"]

您想要访问label元素,它是input:的父元素

$('#priorityContents input[type="checkbox"]:checked').parent();

小提琴在这儿:http://jsfiddle.net/Hk63N/


为了提高性能,您应该考虑拆分选择器:

var priorityText = '';
$('#priorityContents input[type="checkbox"]').filter(':checked').parent().each(function() {
    if ( ! priorityText ) {
        priorityText = priorityText + "|";
    }
    priorityText = priorityText + $(this).text();
});
alert(priorityText);​

来自jQuery文档:

为了在使用这些选择器时获得最佳性能,首先使用纯CSS选择器选择一些元素,然后使用.filter().

这是小提琴:http://jsfiddle.net/Hk63N/1/

根据您发布的代码,您为什么希望看到这样的结果?在该代码中,您从未尝试过检索文本。我建议:

$('#priorityContents input:checkbox:checked').each(function() {
    var next = this.nextSibling,
        text = next.nodeType == 3 ? next.nodeValue : '';
    console.log(text);
});

JS Fiddle演示。

这会迭代给定id元素中的每个选中复选框,查看当前节点的下一个同级节点(不是jQuery对象,而是普通DOM节点),如果该节点是textNodenodeType的节点等于3),则会将nodeValue(该节点的文本内容)分配给变量。

如果它不是textNode,那么它会指定一个空字符串。

您的代码中肯定缺少一些东西。比如#priorityContents元素,如果你正在搜索它,这是非常重要的。

不管怎样,我创建了这个对我有用的演示。基本上你错了,我相信是这个部分:

priorityText = priorityText + $(this).text();

实际的checkbox元素不拥有.text()。您不需要转到父元素来获取其中包含的实际值。

演示

试试这个

var checkedTxt=$('.checkbox :checked').parent().text();
console.log(checkedTxt);

演示

首先,只将文本包装在<label>标记中,这对可用性来说是个好主意。将for属性分配给复选框的ID:

<input type="checkbox" name="priority" id="priority-2" value="2" checked="checked">
<label class="checkbox" for="priority-2">        2 - Critical</label>

然后,您可以使用jQuery选择器轻松实现这一目标:

$('#priorityContents input:checkbox:checked').each(function() {
    priorityText = $('label[for="'+$(this).attr('id')+'"]').text();
    ...
});

也就是说,最简单的方法可能是在复选框的data-prioritytext属性中添加您想要的任何文本,并在代码中使用.data('prioritytext')提取该文本。

var name=$(this).parent().text();

您将获得该复选框的文本在html中,复选框没有用于获取文本数据的属性。所以使用parent()函数获取

您可以使用jquery以这种方式检索选中复选框的文本。

var value = $(document).find('input[type="checkbox"]:checked').attr('value');