0

I am changing Element type in a row of table from

<span class="phoneElement" data-bind="text: Phone"></span>

to

<input type="text" data-bind="textInput:$data.Phone"/>

On a button Click 'Edit', So that I make it editable to user to add new value.

But the issue I am facing is : When it changes to textbox type, it does not hold the data binding (old value) or newly entered data (fresh data). It looks like data binding is not transferred from span to Input.

Richard Rout
  • 1,296
  • 1
  • 15
  • 28
HappyDeveloper
  • 143
  • 1
  • 14
  • you can make `span editable` why not do that approach. just set `'contentEditable',true` – guradio Feb 09 '16 at 04:16
  • What does it have to do with `C#` and `asp.net mvc` tags? – Ghasem Feb 09 '16 at 04:17
  • @HappyDeveloper When you are replacing/changing the Element type, you will need to rebind the data-binding to text box – Haridarshan Feb 09 '16 at 04:38
  • @Alex: As backend is C# and using MVC template – HappyDeveloper Feb 09 '16 at 05:24
  • @guradio and Haridarshan : You are right. I have done the changes to get binding for both the editable and non editable view, just by adding both element with same binding and using Display property to control the display. I have also added logic for cancellable Edit. – HappyDeveloper Feb 09 '16 at 05:30

1 Answers1

3

It's best to not just "change" the element tag, as that's not really a thing (refer to answer: Use jQuery to change an HTML tag?). In short, it isn't the same element anymore. The best way to achieve the same result would be to control via a state property and toggle the view, so something like:

<span class="phoneElement" data-bind="text: Phone, visible: !isEditingPhone(), click: editPhone"></span>
<input type="text" data-bind="textInput: Phone, visible: isEditingPhone, onBlur: doneEditingPhone"/>

You'd then need to implement methods to toggle the isEditingPhone property on the model.

Of course you would be better to encapsulate this logic if you were doing it for a few fields.

Community
  • 1
  • 1
Richard Rout
  • 1,296
  • 1
  • 15
  • 28
  • I did something similar to your answer and it works. Now I have bigger problem. I have a dropdown which is editable. In non editable mode when i bind same property, it actually binds value to it. In my case value is a GUID. Not sure how to get text from this value property. My elements are: – HappyDeveloper Feb 09 '16 at 05:27
  • 1
    @HappyDeveloper If you have a new, seperate problem, it's best to ask a new question (link to the old one, and clarify how it's different). – Jeroen Feb 09 '16 at 06:56