开发者

Setting radio buttons with setField in datalink (jQuery)

I have a need to set radio buttons using the setField() method from datalink (the jQuery plugin).

I have read the issues around this on gitHub and seen a fork to address it (https://github.com/jamiemthomas/jquery-datalink), but this is for older versions of jQuery.

What would be an easy way to updat开发者_StackOverflow社区e radio buttons using the datalink plugin's setField method, perhaps with a slight modification? Maybe there are other alternatives / plugins?


Thanks to a comment from an issue logged on this (https://github.com/jquery/jquery-datalink/issues/14#issuecomment-531732), I have adapted the hack found there. By changing the setField method as follows, it works:

(EDIT - added code for setting checkbox as well).

Before:

    if ( target.nodeType ) {
        var setter = fnSetters[ field ] || "attr";
        $(target)[setter](value);

After:

    if ( target.nodeType ) {
        var setter = fnSetters[ field ] || "attr";
        /* Hack to set radio buttons */
        if ($(target).is(':radio')) {
            $(target).parent().children(":radio[value='" + value + "']").attr('checked', true);
        } else if ($(target).is(':checkbox')) {
            if (target.value == value) $(target).attr('checked', true);
        } else {
            $(target)[setter](value);
        }

EDIT - I have also forked the original datalink project on GitHub and added these changes: https://github.com/mydoghasworms/jquery-datalink/


Updated mydoghasworm's code with the following changes to fix the "cannot uncheck" issue he was facing with the following two code snippets.

            if ( m ) {
                var name = m.name,
                    value = m.value,
                    convert = m.convert;
                if (ev.target.attributes['type'].nodeValue === "checkbox") {
                    value = ev.target.checked;
                }
                if ( convert ) {
                    value = convert( value, ev.target, target );
                }
                if ( value !== undefined ) {
                    $.setField( target, name, value );
                }

Also

} else if ($(target).is(':checkbox')) {
                //value is whether or not checkbox is clicked
                if (value)
                    $(target).attr('checked', true);
                else
                    $(target).removeAttr('checked');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜