Yii2+jQuery实现:当Activity[status]为CANCEL时禁用所有字段
Yii2: Disable All Form Fields When Status is "CANCEL" on Update Page
Got it, let's work through this problem. The core need is to lock down all form fields when the Activity[status] radio button is set to "CANCEL" when the update page loads. I'll also add a little extra logic to handle dynamic radio button changes—just to make the solution more robust, in case someone tries to switch the status after the page loads.
Here's the complete jQuery code you can add directly to your update view (either inline in the view file or in a linked JS asset):
$(function() { // Reusable function to toggle form field enable/disable state function toggleFormFields(shouldDisable) { // Target all form controls in the Activity form - adjust the form ID if yours is different $('#form-activity input, #form-activity select, #form-activity textarea, #form-activity button') .prop('disabled', shouldDisable); // Optional: Uncomment this if you want to keep the status radio buttons usable (to switch back) // $('input[name="Activity[status]"]').prop('disabled', false); } // Check the status immediately when the page finishes loading const currentStatus = $('input[name="Activity[status]"]:checked').val(); if (currentStatus === 'CANCEL') { toggleFormFields(true); } // Listen for radio button changes to update field state dynamically $('input[name="Activity[status]"]').on('change', function() { const newStatus = $(this).val(); toggleFormFields(newStatus === 'CANCEL'); }); });
Quick breakdown of what's happening:
- DOM Ready Wrapper:
$(function() { ... })makes sure our code only runs after all page elements are loaded—so we don't try to select elements that don't exist yet. - Reusable Toggle Function:
toggleFormFieldskeeps our code clean and avoids repetition. We use it both on page load and when the radio button is toggled. - Targeted Selector: We specify the form ID (
#form-activity) to avoid affecting other forms on the page. If your Yii2ActiveFormuses a different ID, update this to match theidproperty you set in the widget. - Optional Radio Button Exception: If you want users to be able to switch the status back from "CANCEL" (which would re-enable the form), uncomment the line that exempts the status radio buttons from being disabled.
This should work out of the box as long as jQuery is loaded on your update page (which it is by default in Yii2 unless you've modified your asset bundles).
内容的提问来源于stack exchange,提问作者Chonjaroen Chauynoo
相关产品推荐
相关产品推荐

