0
votes

I am working with a HTML form with input binding to a Knockout viewmodel. Two of the form inputs are double types for latitude/longitude co-ordinates:

<div class="form-group">
    <input class="form-control" name="Observation.LocationLatitude" data-bind="value: Observation.LocationLatitude" id="latitude" />
    <input class="form-control" name="Observation.LocationLongitude" data-bind="value: Observation.LocationLongitude" id="longitude" />
</div>

I update these from my Google Maps javascript function like this:

document.getElementById('latitude').value = markers[0].position.lat();
document.getElementById('longitude').value = markers[0].position.lng();

The code updates the input fields, but does not update the binding to the viewmodel.

The only way the viewmodel is updated is if I type directly to the input field. Following the documentation, I have tried the "textInput" binding, as well as the value input binding without success. I have also tried to set/update the focus of the input field in the Javascript. That also did not work.

Does anyone know if it is possible to update the binding from Javascript?

1

1 Answers

1
votes

Let knockout do the heavy lifting for you - you instead just need to worry about updating your model, knockout will update the view. Assuming your model properties are observables:

Observation.LocationLatitude(markers[0].position.lat());
Observation.LocationLongitude(markers[0].position.lng());

Generally if you're using knockout to manage the DOM, you want to stay away from updating it directly (including the value of inputs, as you're attempting here), as at the very least knockout will be unaware of the updates (as here), or worse it causes conflicts and errors.