briank
briank

Reputation: 83

KnockoutJS change value and text of input on checkbox change event

I have a list of skills and when the user checks the skill an input for years will then display if checked. My issue is if user enters a year but then un-checks the skill the value for years is still saved in the observable along with the text on the input. I am not sure if i need to clear the value out with an event handler, subscribe function, or just a ko computed function.

http://jsfiddle.net/bjk964/CQ2CG/2/

<div data-bind="foreach: ApplicationSkills">                
    <p>
        <span data-bind="text: Skill_SkillTypeName"></span>
        <input type="checkbox" data-bind="checked: Skill_Checked" />
        <span data-bind="visible: Skill_Checked" class="years">Years:</span>
        <input type="text" data-bind="value: Skill_Years, visible: Skill_Checked" />
    </p>                
</div>

var Application = function () {
    this.ApplicationSkills = ko.observableArray();
};

var ApplicationSkill = function () {
    var self = this;
    this.Skill_SkillTypeID = ko.observable(0);
    this.Skill_Years = ko.observable().extend({ maxLength:2, number:true });
    this.Skill_Checked = ko.observable(false);
    this.Skill_SkillTypeName = ko.observable();
};

var vm = new Application();
ko.applyBindings(vm);

var skill = new ApplicationSkill()
skill.Skill_SkillTypeID(1);
skill.Skill_SkillTypeName('Data Entry');

vm.ApplicationSkills.push(skill); 

Upvotes: 1

Views: 1488

Answers (1)

Brandon
Brandon

Reputation: 39212

I'd do it as a computed:

var skillYears = ko.observable();
this.Skill_Years = ko.computed({
    read: function () { return this.Skill_Checked() ? skillYears() : undefined; },
    write: skillYears
}, this);

Upvotes: 2

Related Questions