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
  • 52,576
  • 15
  • 105
  • 143
Haradzieniec
  • 8,592
  • 29
  • 109
  • 204

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
  • 23,299
  • 8
  • 73
  • 108
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,569
  • 5
  • 35
  • 53
Rajagopal 웃
  • 7,381
  • 7
  • 29
  • 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