Question

Solved by @Grundy, solution at bottom of post

I have a form with a radio option where the elements are selected programmatically and without the user directly clicking on the radio element.

var $elem = $("input[name=type][value^=foo_]"); // Select the element with name "type" where the value starts with "foo_" (assume only one value is ever found)
if ($elem.length > 0) // If element is found then toggle the checked value of the radio value
{
    $("input[name=type][checked=checked]").attr("checked", false); // Uncheck all existing checked items
    $elem.attr("checked", true); // Check the found element from before
}

This works, I can see the attributes change in Chrome's developer tools. The previous checked input is unchecked and the appropriate item becomes checked. This works every time specifically works multiple times (I'll explain why that's relevant later).

Next I hide all the unchecked radio buttons and show only the checked one.

$("input[name=type] + label").hide();
$("input[name=type]:checked + label").show();

This works the first time an input is selected. All the unchecked inputs will be hidden and the checked one will be unhidden. If the input is selected a second time (either immediately again or after other options have been selected in between) then all of the inputs are hidden including the checked one.

If I check the number of matched elements for $("input[name=type]:checked + label") it returns 1 for the first time and 0 for the second time meaning it won't be selected only after the second time. I feel like this is because the checked attribute has been changed dynamically at that point but that may not be the cause of the problem.

EDIT - Here's a Fiddle fiddle Clicking on the gray box will show you its normal behavior when changed by the user clicking on the values. Each value can be selected multiple times in any order but if you click the text at the bottom (they're poor looking buttons) it will change the form programmatically. It only works for the first time, it does not seem to care if it was selected by the user previously.

Solution - Credit @Grundy Since I know the $elem object I found earlier is the object being changed I can reference it directly instead of trying to search for an element with the checked attribute. So I use this:

var $elem = $("input[name=type][value^=foo_]"); // Created before all the changes
$elem.next("label").show(); // Referenced after all the changes

Instead of using this:

$("input[name=type]:checked + label").show(); // Referenced after all the changes
Was it helpful?

Solution

try use

$elem.next("label").show();

instead of

$("input[name=type]:checked + label").show();

because $elem is checked checkbox that you find

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top