Ben Ben - 6 months ago 21
jQuery Question

Knockout.js Change form value based on another form value

Hi I have a form that contains a yes/no radio button group and another group with about 3 radio button values.

I'm trying to achieve a dynamic where if the value of the first question is 'no' it will select a specific radio button in the second group and disable the user from changing the value. If the user selects 'Yes' they can then pick any option they want from the second group.

I have the disable on condition functionality working correctly but I am struggling to get the functionality to select the '0' radio button in the second group if the 'No' option is selected in the first

My code is:

this.isEligibleStateBenefitCd = ko.observable(args.isEligibleStateBenefitCd);
this.weeklyPrsiContributionsRate = ko.computed(args.weeklyPrsiContributionsRate);


HTML:

<div tabindex="0" class="radio-group" typeof="select_box">
<input data-bind="checked: isEligibleStateBenefitCd" value="Y" type="radio" name="isEligibleStateBenefitCd"/> Yes
<input data-bind="checked: isEligibleStateBenefitCd" value="N" type="radio" name="isEligibleStateBenefitCd"/> No
</div>

<div tabindex="0" class="radio-group" typeof="select_box" data-bind="enable: isEligibleStateBenefitCd() === 'Y'">
<input data-bind="checked: weeklyPrsiContributionsRate" value="238.30" type="radio" name="weeklyPrsiContributionsRate" id="48"> 48 or Over
<input data-bind="checked: weeklyPrsiContributionsRate" value="233.60" type="radio" name="weeklyPrsiContributionsRate" id="4047"> 40-47
<input data-bind="checked: weeklyPrsiContributionsRate" value="0" type="radio" name="weeklyPrsiContributionsRate" id="0"> N/A - €0
</div>

Answer Source

Try to use subscribe. Take a look at: http://knockoutjs.com/documentation/observables.html

It will trigger every time your isEligibleStateBenefitCd change.

self.isEligibleStateBenefitCd.subscribe(function(newValue) {
   if(newValue == 'N'){
      self.weeklyPrsiContributionsRate('0');
   }
});

For disable dont use it on div, try it:

<input data-bind="checked: weeklyPrsiContributionsRate,enable: isEligibleStateBenefitCd() === 'Y'" value="238.30" type="radio" name="weeklyPrsiContributionsRate" id="48"> 48 or Over

<input data-bind="checked: weeklyPrsiContributionsRate,enable: isEligibleStateBenefitCd() === 'Y'" value="233.60" type="radio" name="weeklyPrsiContributionsRate" id="4047"> 40-47

<input data-bind="checked: weeklyPrsiContributionsRate" value="0" type="radio" name="weeklyPrsiContributionsRate" id="0"> N/A - €0

Working Example: https://jsfiddle.net/wp8Lwgem/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download