如何在JavaScript中获取Kartik radioList选中值并实现文本框显隐?
Let's fix your code step by step to achieve both showing/hiding the textbox based on the selected radio option and getting the selected value correctly.
First, Understand the Issue with Your Current Code
The id="rdo" you added to the radioList is applied to the container element wrapping all radio buttons, not the individual radio inputs themselves. So your $("#rdo").click() is listening for clicks on the entire container, which isn't precise. Also, there's no #rdo1 element generated by Yii's radioList—each radio button will have an ID like ModelName-rdo-0 (for "Free") and ModelName-rdo-1 (for "Paid") instead.
Fixed JavaScript Code
Here's the corrected code that handles both the visibility toggle and value retrieval:
$(document).ready(function(){ // Listen for change events on any radio button inside the #rdo container $("#rdo input[type='radio']").on('change', function(){ // Get the selected radio value const selectedValue = $("#rdo input[type='radio']:checked").val(); // Toggle textbox visibility based on selection: Show when "Free" (value 0) is selected if(selectedValue === "0"){ $("#name").show(); } else { $("#name").hide(); } // Optional: Log the selected value for testing console.log("Selected Contribution Type:", selectedValue === "0" ? "Free" : "Paid"); }); // Initialize the textbox state on page load (in case a radio is pre-selected) const initialSelectedValue = $("#rdo input[type='radio']:checked").val(); if(initialSelectedValue !== "0"){ $("#name").hide(); } });
Key Notes:
- Retrieving Selected Value:
$("#rdo input[type='radio']:checked").val()targets the checked radio button inside your radioList container, so you don't have to worry about the auto-generated IDs from Yii. - Event Listening: Using
changeinstead ofclickis more reliable, as it triggers only when the selection actually changes. - Initial State: The extra code checks for a pre-selected radio button when the page loads, ensuring the textbox starts in the correct state.
If You Prefer Using the Radio Button Name
You can also target the radio buttons by their name attribute (which Yii generates as Model[rdo], replace Model with your actual model class name):
// Alternative way to get selected value const selectedValue = $("input[name='Model[rdo]']:checked").val();
内容的提问来源于stack exchange,提问作者Zoe

