简体   繁体   中英

Cannot programmatically select radio button if preventDefault() called

I've got a 'catch 22' in Chrome. I cannot programmatically select a radio button within a click event if any other function bound to the same event makes a call to preventDefault() .

For example, I have a radio button with a parent element bound to a click event in which preventDefault() is called. If the radio button is clicked directly it is not checked. This is to be expected. However, I actually need the radio button to be selected so within code I attempt to check it in another function bound to the click event: $(this).prop('checked', true); .

Oddly, this doesn't work and I cannot remove the call to preventDefault() or disable propagation because it is in third party code that I need to run.

Is this a bug? Any suggested workarounds?

Here is an example: http://jsfiddle.net/LnLuk4st/

UPDATE:

I have tried @RGraham's suggestion. His example clearly works, but oddly it does not work in the context of my code . @RGraham's code had a syntax error which made it appear to be working.

Here's some context:

// Remember kendo tab
$(".k-tabstrip").each(function () {
    var $tabStrip = $(this);
    var $tabs = $tabStrip.find(".k-tabstrip-items .k-item");
    var tabCookie = "Current_Tab_" + $tabStrip.attr("id");

    // On tab change, set cookie
    $tabs.click(function () {
        createCookie(tabCookie, $(this).attr("aria-controls"), 1);
        $tabStrip.parent().css({ 'min-height': $tabStrip.parent().height() });


        if ($(this).is('input')) { // Doesn't eval to true, 'this' is always a '.k-item'.
            $(this).prop("checked", true);
        } else {
            // Never works if the input is clicked directly
            $(this).find('input').prop("checked", true);
        }


    });

    // @RGraham's suggestion...
    $tabs.on('click', 'input', function() {
        $(this).prop("checked", true); // Line reached but doesn't work either :(
    });

    // If cookie set, select tab
    var tab = readCookie(tabCookie);

    if (tab) {
        $tabs.each(function () {
            if ($(this).attr("aria-controls") == tab) {
                $(this).click();
            }
        });
    }
});

I still believe this behaviour to be a bug but I have found a workaround.

Capture the click of the radio button directly, prevent propagation, then programmatically click the parent of the radio button. This allows the third party code to run without applying preventDefault to the radio button.

    // preventDefault bug fix.
    $tabs.find("input").click(function (e) {
        e.stopPropagation();
        $(this).parent().click();
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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