查找所选单选按钮的文本

时间:2013-05-10 16:53:21

标签: jquery

这是我动态生成的html单选按钮列表

<label class="radio" for="10013"><input type="radio" name="himg" value="10013">Amr1a</label> 

<label class="radio" for="10014"><input type="radio" name="himg" value="10014"> Amr2a</label>

想要选择点击(选中)单选按钮的文字

这就是我尝试过的(jquery-1.9.1)

$(document.body).on('click', 'input:radio[name="himg"]', function () {
                alert($(this).next().text());

            });

但它没有任何回报。

5 个答案:

答案 0 :(得分:3)

变化:

alert($(this).next().text());

为:

alert($(this).parent().text());

<强> jsFiddle example

您正在点击单选按钮元素,然后尝试使用.next()查找没有的下一个元素,只查找文本节点。通过使用.parent(),您可以获取标签内的文本(不包括广播的HTML)。

答案 1 :(得分:3)

您不需要bodynext() ... next()搜索下一个DOM元素,但在您的情况下是text..so 使用parent()和text()

试试这个

$(document).on('click', 'input:radio[name="himg"]', function () {
            alert($(this).parent().text());

        });

答案 2 :(得分:3)

试试这个:

$(document).on('click', 'input:radio[name="himg"]', function () {
    alert($(this).parent().text());
});

实际上,label这里是所选单选按钮的parent,而不是紧跟兄弟姐妹。 因此,我们需要使用parent()来获取label元素,然后使用它的文本。

答案 3 :(得分:2)

通过提供无线电ID并使用label-for属性将其与标签相关联来利用for

Refer label usage

Demo

HTML

<input type="radio" id="radio1" name="himg" value="10013" />
<label class="radio" for="radio1">Amr1a</label>
<input type="radio" id="radio2" name="himg" value="10014" />
<label class="radio" for="radio2">Amr2a</label>

JS

$(document.body).on('click', 'input:radio[name="himg"]', function () {

    alert($('label[for=' + this.id + ']').text()); // Ids are going to be unique so yuo can directly select it with label for.

});

答案 4 :(得分:1)

通过对代码进行一些调整,以下内容应该有效:

   $(document.body).on('click', 'input:radio[name="himg"]', function () {
      alert($(this).closest('label').text());
    });
相关问题