Ruslan
Ruslan

Reputation: 10147

KnockoutJS observable doesn't observe jQuery's empty() event

I have a couple of textboxes: local & foreign phone numbers and a checkbox to toggle them, like so:

  TogglePhoneFields = function(isForeign) {
    if (isForeign) {
      $('#Phone_LocalNumber').attr('disabled', 'disabled');
      $('#Phone_LocalNumber').val('');
      $('#Phone_ForeignPhoneNumber').removeAttr('disabled');
      return $('#Phone_ForeignPhoneNumber').focus();
    } else {
      $('#Phone_LocalNumber').removeAttr('disabled');
      $('#Phone_ForeignPhoneNumber').attr('disabled', 'disabled');
      return $('#Phone_ForeignPhoneNumber').val('');
    }
  };

Mark-up:

<input data-bind="value: localnumber" 
    id="Phone_LocalNumber" type="text" value='' />

<input data-bind="checked: isForeignPhoneNumber" 
    id="Phone_IsForeignPhoneNumber" type="checkbox" value="true" />

<input data-bind="value: foreignphonenumber" 
    id="Phone_ForeignPhoneNumber" type="text" value="" />

And I have validation on these phone nums where it becomes clear that after you input a value in the local phone number, tick the "IsForeign" checkbox (it calls TogglePhoneFields(true) ) and untick it, the observable values are not cleared.

I'm struggling to explain this, I could write a jsFiddler if it isn't clear at all. The question basically is how to update observable item when its value is manipulated by javascript code?

Upvotes: 0

Views: 599

Answers (1)

madcapnmckay
madcapnmckay

Reputation: 15984

Knockout value bindings subscribe to change events on the inputs they are bound to. If you update an input in jquery using val you need to fire a change event or the value binding will not be triggered.

So for example

$('#Phone_LocalNumber').val('').change();

Hope this helps.

Upvotes: 2

Related Questions