实现单选按钮选中值自动填充至输入文本框的Knockout.js问题
Hey there, let's get this working properly. I spotted a handful of issues in your code that are stopping the radio button selection from updating the input field as expected. Here's the breakdown and the fixed version:
Key Issues in Your Original Code
- No binding on radio buttons: Your radio buttons aren't linked to your ViewModel, so Knockout can't track when their selection changes.
- Incorrect observable naming: You assigned the initial gender value to
lastNameinstead of a dedicatedgenderobservable, which your computed property tries to reference. - Conflicting property names: You used
firstNamefor a computed property, but your input field is bound to that same name—yet you didn't define a separate observable to store the user's actual first name input. - Case-sensitive typo: You wrote
this.firstname()(lowercase 'n') instead ofthis.firstName()(uppercase 'N') in your computed function.
Fixed Code
HTML
<div class='liveExample'> <input type="radio" name="gender" value="Mr." data-bind="checked: gender" checked>Mr. <input type="radio" name="gender" value="Mrs." data-bind="checked: gender">Mrs. <p>First name: <input data-bind='value: firstNameInput' /></p> <p>Combined name: <input data-bind='value: combinedName' readonly /></p> </div>
JavaScript
var ViewModel = function(initialGender) { // Track the selected radio button value this.gender = ko.observable(initialGender); // Track user's input for first name this.firstNameInput = ko.observable(""); // Computed property to combine gender prefix and first name this.combinedName = ko.computed(function() { // Add space between prefix and name only if name is entered return this.gender() + (this.firstNameInput() ? " " + this.firstNameInput() : ""); }, this); }; // Initialize ViewModel with default checked gender ko.applyBindings(new ViewModel("Mr."));
What This Fixes
- The radio buttons now use
data-bind="checked: gender"to link directly to the ViewModel'sgenderobservable—selecting a button updates the ViewModel instantly. - We have a separate
firstNameInputobservable to store the user's typed first name, avoiding conflicts with the computed combined value. - The
combinedNamecomputed property automatically updates whenever either the radio selection or first name input changes, exactly matching your requirement to add the radio's value to the input field. - The readonly field shows the final combined result clearly—if you want the main input to display the combined value instead, you can adjust the bindings to use
combinedNamewith a write function, but this setup follows Knockout's best practices for separation of concerns.
内容的提问来源于stack exchange,提问作者Shyam Acharya
相关产品推荐
相关产品推荐

