Tauheed yar khan
Tauheed yar khan

Reputation: 77

Knockoutjs:bind multiple html elements with same viewModel's property

I want to bind single viewModel's property with two html elements but its not working. It's binding the model's property only to the first element.The reason for doing this is that I want to show a form with same data (both edit and read only views of form). Kindly suggest if there is any better approach to solve this problem(to provide edit/readonly view for form easily) .

Following is what I wanted to do right now.

<span data-bind="text: name"/>
<input data-bind="value: name" />

Upvotes: 1

Views: 950

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074455

The problem is that your span isn't closed. You can't use <span/> because span is not one of the void elements. (Self-closing tags are only for elements that cannot contain anything, like <br/> or <input/>; you only need the / in them for XHTML, although it's allowed in HTML [it's just meaningless].) So since the span isn't closed, the browser has to guess what you meant the span to contain; when KO sets the span's contents, it wipes out everything the browser guessed was inside the span.

If you close the span correctly, it works:

<span data-bind="text: name"></span>
<input data-bind="value: name" />

Live example | source

Upvotes: 4

Related Questions