0

The jQuery code looks like this and works fine (probably it look a bit sorter, so please let me know and I'll change it either): jsFiddle

jQuery:

$('.inputs').on('keyup',function(){
    $(this).parent().not(this).find('.inputs').val($(this).val());
}
);

HTML:

<div>
    <input type="text" class="inputs" value="hello">
    <input type="text" class="inputs" value="John">
</div>

How can I rewrite this code for knockout.js?

Thank you.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

2 Answers2

1

Just bind it to the same observable:

HTML

<div>
    <input type="text" class="inputs" id="first" data-bind="value:foobar,valueUpdate:'keyup'">
    <input type="text" class="inputs" id="second" data-bind="value:foobar,valueUpdate:'keyup'">
</div>

ViewModel

function AppViewModel() {
    this.foobar = ko.observable('hello');
}
ko.applyBindings(new AppViewModel());

I used the valueUpdate binding to update the inputs in real time instead of on blur (see also: https://stackoverflow.com/a/4391419/664108)

Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
1

Take a look at the below code snippet which will work fine with ko.

var value = "Hello John";
var viewModel = {
  Name: ko.observable(value)
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" data-bind="value:Name" class="inputs" id="first">
  <input type="text" data-bind="value:Name" class="inputs" id="second">
</div>
<span data-bind="text: Name"> </span>

Hope, You will do this with more data. In that case, Take a look at this sample which will let you know about how to support more data.

For more faqs visit jqfaq.com

Brant Olsen
  • 5,628
  • 5
  • 36
  • 53
Rajagopal 웃
  • 8,061
  • 7
  • 31
  • 43
  • I don't think your fiddle does exactly what @Haradzieniec has requested. Instead you would need to add `valueUpdate:'keyup'` as an additional `data-bind` binding. – edhedges Mar 06 '13 at 20:34