jQuery不返回已检查的无线电值

时间:2010-07-17 07:29:26

标签: jquery jquery-selectors

更新: 问题更复杂。看起来它涉及手风琴标题没有正确传递.click事件,并且与选中的选择器无关。所有这个例子都可以在测试文件中正常工作。

请参阅Radio input in header of accordion problem ?BUG

我有一个带有几个无线电元素的表单,每个名称都应用“rx”(其中x是1..3),.buttonset()。 与

例如id = 3

alert ($('input:radio[name=r'+id+']').val());
//returns value of the first radio in the set

alert ($('input:radio[name=r'+id+']:checked').val());
//returns 'undefined', even one of the radios is checked.

我已尝试:checked')[0]:checked').get(0):checked').attr('id')

我想知道为什么第一个方法返回一个值...它是否与.buttonset添加类/元素有关?

感谢任何建议!

PS。 $( '输入:无线​​电[名称= R' + ID + ']')得到(0)。 返回[object HTMLInputElement],我猜它应该是这样的。但是这个对象没有.html()或.val()方法。 $('input:radio [name = r'+ id +']:checked')。get(0)仍然是'undefined'。

PPS。强制ui-helper-hidden-accessible的可见性 buttonset不会更改原始无线电元素的“已选中”。 我想我可以使用.ui-state-active来检查有效的无线电......有没有更好的方法?

4 个答案:

答案 0 :(得分:1)

它不返回值的原因是因为当您使用:checked选择器时如果未选择无线电,则它不会成为结果集的一部分。例如:

<input type="radio" name="r1" value="1" checked="checked" />
<input type="radio" name="r2" value="2" />

现在:

alert($('input:radio[name=r1]').val()); // alerts 1
alert($('input:radio[name=r1]:checked').val()); // alerts 1
alert($('input:radio[name=r2]').val()); // alerts 2
alert($('input:radio[name=r2]:checked').val()); // alerts undefined as the button is not selected

答案 1 :(得分:0)

试试这个 -

$("input[name='radio_name']:checked").val();

答案 2 :(得分:0)

阅读有关选择器的页面,尤其是这一个http://api.jquery.com/attribute-starts-with-selector/

alert ($(':radio[name^=r]:checked').val());

应该返回选中按钮的值,如果没有选择则返回undefined。

答案 3 :(得分:0)

我写了一个jQuery插件,用于设置和获取单选按钮值。它还尊重他们的“改变”事件。

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

将代码放在任何位置以启用插件。然后享受!它只是覆盖了默认的val函数而没有破坏任何东西。

你可以访问这个jsFiddle来试一试它,看看它是如何工作的。

http://jsfiddle.net/ffMathy/MN856/