jQuery 如何获取复选框的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19434241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:56:40  来源:igfitidea点击:

How I can get the text of a checkbox?

javascriptjqueryformscheckbox

提问by Jorge H

I have the following set of checkboxes:

我有以下一组复选框:

<ul class="checkbox_list">
 <li><input name="mensajes[receptores_list][]" type="checkbox" value="5" id="mensajes_receptores_list_5" />&nbsp;<label for="mensajes_receptores_list_5">Carlos (Admin)</label></li>
<li><input name="mensajes[receptores_list][]" type="checkbox" value="1" id="mensajes_receptores_list_1" />&nbsp;<label for="mensajes_receptores_list_1">Jorge (Admin)</label></li>
<li><input name="mensajes[receptores_list][]" type="checkbox" value="3" id="mensajes_receptores_list_3" />&nbsp;<label for="mensajes_receptores_list_3">Marisa (Admin)</label></li>
<li><input name="mensajes[receptores_list][]" type="checkbox" value="6" id="mensajes_receptores_list_6" />&nbsp;<label for="mensajes_receptores_list_6">Christian (Apuntes)</label></li>
<li><input name="mensajes[receptores_list][]" type="checkbox" value="4" id="mensajes_receptores_list_4" />&nbsp;<label for="mensajes_receptores_list_4">Julieta (Contable)</label></li>
<li><input name="mensajes[receptores_list][]" type="checkbox" value="2" id="mensajes_receptores_list_2" />&nbsp;<label for="mensajes_receptores_list_2">Vicky (Contable)</label></li>
</ul> 

Using javascript, how I can access the text of each item. For example, for the element with id = "mensajes_receptores_list_5" I want to get the text "Carlos (Admin)"

使用 javascript,我如何访问每个项目的文本。例如,对于 id = "mensajes_receptores_list_5" 的元素,我想得到文本 "Carlos (Admin)"

采纳答案by Manish

By Jquery

通过 Jquery

 function getLabel(id)
   {
  return $("#"+id).next("label").html();
   }

  //id of checkbox ,you want to get label of
  var label=getLabel('mensajes_receptores_list_1'); 
  alert(label);

Jsfiddle http://jsfiddle.net/pcQgE/1/

jsfiddle http://jsfiddle.net/pcQgE/1/

回答by kjelderg

I would approach it like this:

我会这样处理它:

function getLabelText(needle) {
    var labels = document.getElementsByTagName("label");
    var texts = [];
    for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        if(label.getAttribute("for") == needle) {
            console.log(label.innerText);
            texts.push(label.innerText);
        }
    }
    return texts;
}

回答by Hat

Here's a modern vanilla JS solution that should work for the general case of finding the label associated with a checkbox:

这是一个现代 vanilla JS 解决方案,它应该适用于查找与复选框关联的标签的一般情况:

function getCheckboxLabel(checkbox) {
    if (checkbox.parentNode.tagName === 'LABEL') {
        return checkbox.parentNode
    }
    if (checkbox.id) {
        return document.querySelector('label[for="' + checkbox.id + '"]')
    }
}

Because according to this SO answer, there are two ways to create the association between the <input>and <label>:

因为根据this SO answer,有两种方法可以在<input>和之间创建关联<label>

First, you can wrap the label element around the input element:

<label>Input here:
    <input type="text" name="theinput" id="theinput">
</label>

The other way is to use the forattribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type="text" name="whatever" id="theinput">

首先,您可以将 label 元素包裹在 input 元素周围:

<label>Input here:
    <input type="text" name="theinput" id="theinput">
</label>

另一种方法是使用该for属性,为其提供关联输入的 ID:

<label for="theinput">Input here:</label>
<input type="text" name="whatever" id="theinput">

So to answer the original question of how to get the text, you would simply use this function along with textContent:

因此,要回答有关如何获取文本的原始问题,您只需将此函数与textContent

function getCheckboxLabel(checkbox) {
    if (checkbox.parentNode.tagName === 'LABEL') {
        return checkbox.parentNode
    }
    if (checkbox.id) {
        return document.querySelector('label[for="' + checkbox.id + '"]')
    }
}

let checkboxes = document.querySelectorAll('input[type=checkbox]')
checkboxes.forEach((checkbox) => {
    let label = getCheckboxLabel(checkbox)
    if (label) {
        console.log('label text:', label.textContent)
    } else {
        console.log('could not find the label of', checkbox)
    }
})
<!-- Sample HTML taken from OP -->
<ul class="checkbox_list">
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="5" id="mensajes_receptores_list_5" />&nbsp;<label for="mensajes_receptores_list_5">Carlos (Admin)</label></li>
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="1" id="mensajes_receptores_list_1" />&nbsp;<label for="mensajes_receptores_list_1">Jorge (Admin)</label></li>
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="3" id="mensajes_receptores_list_3" />&nbsp;<label for="mensajes_receptores_list_3">Marisa (Admin)</label></li>
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="6" id="mensajes_receptores_list_6" />&nbsp;<label for="mensajes_receptores_list_6">Christian (Apuntes)</label></li>
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="4" id="mensajes_receptores_list_4" />&nbsp;<label for="mensajes_receptores_list_4">Julieta (Contable)</label></li>
    <li><input name="mensajes[receptores_list][]" type="checkbox" value="2" id="mensajes_receptores_list_2" />&nbsp;<label for="mensajes_receptores_list_2">Vicky (Contable)</label></li>
</ul>

回答by gp.

you can use sibling selector:

您可以使用兄弟选择器:

var id = "mensajes_receptores_list_5"
alert( document.querySelector("#"+id+"+ label").innerText );

回答by R. Oosterholt

You can use jQuery. Example:

您可以使用jQuery。例子:

var label = $("#mensajes_receptores_list_5").next("label").text();
alert(label)

回答by Alex W

This will iterate through and print all of the text to the console. You could also get a specific one by using if(i == 3)for example.

这将遍历并将所有文本打印到控制台。您还可以通过使用if(i == 3)例如来获得特定的。

var labels = document.getElementsByTagName('label');

for(var i = 0; i < labels.length; i++)
{
    console.log(labels[i].innerHTML);
}

http://jsfiddle.net/pcQgE/

http://jsfiddle.net/pcQgE/

回答by Todd

Most modern browsers allow you to access the label(s) associated with an input element via the labelsproperty.

大多数现代浏览器允许您通过labels属性访问与输入元素关联的标签。

const inputs = document.getElementsByTagName("input");
console.log(`First label for first element is: $inputs[0].labels[0].innerText`)

From the HTML Spec:

HTML 规范

Labelable elements and all input elements have a live NodeList object associated with them that represents the list of label elements, in tree order, whose labeled control is the element in question. The labels IDL attribute of labelable elements that are not form-associated custom elements, and the labels IDL attribute of input elements, on getting, must return that NodeList object, and that same value must always be returned, unless this element is an input element whose type attribute is in the Hidden state, in which case it must instead return null.

可标记元素和所有输入元素都有一个与之关联的活动 NodeList 对象,该对象表示按树顺序排列的标签元素列表,其标记控件是相关元素。不是表单关联的自定义元素的可标签元素的标签 IDL 属性和输入元素的标签 IDL 属性在获取时必须返回该 NodeList 对象,并且必须始终返回相同的值,除非该元素是输入元素其 type 属性处于 Hidden 状态,在这种情况下,它必须改为返回 null。

Browser compatibility can be found at this caniuse.com link

浏览器兼容性可在此caniuse.com 链接中找到