繁体   English   中英

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

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

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

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 不建议使用:checkbox选择器,您可以使用input[type="checkbox"]代替。

根据您发布的代码,您为什么期望看到该结果? 在该代码中,您没有尝试检索文本。 我建议:

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

JS小提琴演示

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

如果它不是textNode ,则它会分配一个空字符串。

您想要到达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/

首先,将文本仅包装在<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')提取。

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

无论如何,我创建了这个适合我的演示。 基本上你错了我相信这部分:

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

实际的checkbox元素不拥有.text()。 你需要去父母那里获得那里包含的实际价值。

DEMO

尝试这个

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

DEMO。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM