Gandalf
Gandalf

Reputation: 13683

Dragged item does not stay on its new position

I am having this code which i am using to dynamically add new items

 <!Doctype html>
    <head>
    <meta charset="utf-8">
    <style type="text/css">
    .tr_deco{
    background-color:pink;
    border:1px solid red;
    }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
    <script type="text/javascript">
    jQuery(function() {
    jQuery(".new_krud_slider").click(function(e){
    e.preventDefault();
    jQuery('.krud_dom').append("<form name='krud_submit' action='admin.php?page=exchange_page' method='post'><table class='sortable'><tr class='tr_deco'><td>Slider Title</td><td><input type='text' /></td><td>Slider Description</td><td><textarea></textarea></td><td>Slider Location</td><td><input type='text' name='x' value='Jenna Doe'/></td><td><a href=''>I</a></td></tr><tr class='tr_deco'><td></td><td></td><td></td><td></td><td></td><td><button>Save</button></td><td><button>Delete</button></td></tr></table></form>");
jQuery( ".sortable" ).sortable();
    });
    });
    </script>
    </head>
    <body>
    <a class="new_krud_slider" href="">make new</a>
    <table>
    <tr><td class="krud_dom"></td></tr>
</table>
    </body>
    </html>

​Here is the fiddle http://jsfiddle.net/TRJXe/ I need the dragged item to stay where it has been dropped.

Upvotes: 0

Views: 211

Answers (1)

jackwanders
jackwanders

Reputation: 16010

You're using the sortable jQuery widget. You need to use the draggable widget

jQuery( ".sortable" ).draggable();

This will let the item stay where it's dragged. Using sortable lets you drag items, yes, but when you let go, the item automatically sorts into its new location. Since you only have one item, it will always sort to the top; this is why it jumps back to the same spot after you let go of it.

UPDATE

After clarification on the nature of the question, the source of your problem is that you're calling .sortable on each individual form. To properly use the sortable jQuery UI widget, you need to call .sortable() on the element that contains all the elements you want to sort. In this case, that would be .krud_dom

So, you'll want to start by calling .sortable on .krud_dom, like so:

jQuery( ".krud_dom" ).sortable();

Then, each time you add a new form to the page, you need to "refresh" the widget, with another call to .sortable:

jQuery( ".krud_dom" ).sortable("refresh");

I've created a jsFiddle demo showing how this works:

--- jsFiddle DEMO ---

Upvotes: 1

Related Questions