Question

I want to implement a form builder using knockout and JQuery UI.

I found Knockout sortable plugin plus some more material and I implemented a framework for the form builder.

Basically I have an observable array that holds all my available field types with their proprieties and another one that holds the controls that have been added to the form. I added a binding that would add me a field just by clicking on it so it would save the fast users from the time of dragging and dropping. Also a click event on the added fields that would go to the field details (now only displays an alert).

I want to assign an id for every form element that is added to the form. If another element is added to the form it should have an incremented id and if the elements within the form are rearranged the id's of the elements should be changed as well.

My question is where and how should I perform this ID assignment and then reassignment so every time a new field is added or moved around the id's of the form element would be in consecutive order.

I assume that I could assign an id for every dropped element in the binding handler but how can I control it afterwards?:

$(element)[0].id = 'field-nr-' + globalVariable++;

This would also mean that I have to change the Knockout Sortable plug-in, witch I'm trying to avoid.

The code is in this fiddle : http://jsfiddle.net/razvangl/z52G7/

Was it helpful?

Solution

If I understand this correctly, then you could probably use the $index observable that is available when binding in a foreach.

So, you would bind something like:

<table style="width : 100%" data-bind="attr: { id: 'field-nr-' + $index() }" >

As you drag the fields around, the id will remain updated based on its position in the observableArray.

I updated your fiddle (and updated the KO version) to show the the value in a td: http://jsfiddle.net/rniemeyer/56PLd/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top