如何通过jQuery获取指定ID容器内选中的类为option的单选框值
Let's break down what's going wrong here and fix it step by step.
问题1:第一种写法返回undefined
Your first code snippet $value = $($check +' .option:checked').val(); fails because the selector is missing the # symbol for ID targeting. Since $check is the string "quiz1", the concatenated selector becomes "quiz1 .option:checked" — which looks for elements with the class quiz1 instead of the ID quiz1. No matching elements are found, hence undefined.
问题2:第二种写法 throws a syntax error
The error Uncaught Error: Syntax error, unrecognized expression: #[object Object] .option:checked tells us that $check isn't actually the string "quiz1" — it's a jQuery object. This almost always happens when you accidentally omit .attr('id') when assigning the variable:
// Wrong: assigns a jQuery object instead of the ID string $check = $(this).closest('ul').parent();
When you concatenate a jQuery object with a string, it converts to [object Object], breaking the selector syntax entirely.
Solutions
Solution 1: Fix the selector and ensure $check is a string
First, confirm you're correctly fetching the ID string:
// Make sure this returns the string "quiz1", not a jQuery object const checkId = $(this).closest('ul').parent().attr('id'); console.log(checkId); // Verify in your browser's console
Then use the correct ID selector syntax:
const selectedValue = $('#' + checkId + ' .option:checked').val();
Solution 2: Robust chained lookup (Recommended)
You don't need to rely on ID concatenation at all. Instead, chain your selectors directly from the context you already have — this is cleaner and avoids ID-related bugs entirely:
const selectedValue = $(this).closest('ul').parent().find('.option:checked').val();
This method directly targets the parent container (your #quiz1 div) and searches within it for the checked radio button, which is especially reliable for PHP-generated dynamic elements.
Full Example
Assuming your PHP-generated HTML looks like this:
<div id="quiz1" class="quiz-container"> <ul> <li> <input type="radio" class="option" name="quiz1" value="A"> Option A <input type="radio" class="option" name="quiz1" value="B" checked> Option B </li> </ul> </div>
Working JavaScript code would look like this:
// Example event handler (adjust to match your trigger) $('.option').change(function() { // Solution 1: Using ID const checkId = $(this).closest('ul').parent().attr('id'); const value1 = $('#' + checkId + ' .option:checked').val(); console.log(value1); // Outputs "B" // Solution 2: Chained lookup (cleaner) const value2 = $(this).closest('ul').parent().find('.option:checked').val(); console.log(value2); // Outputs "B" });
If you still run into issues, start by checking the value of checkId in your browser's console — confirming it's the string "quiz1" is the key first step.
内容的提问来源于stack exchange,提问作者VikashSDNT

