netrox netrox - 3 months ago 7
jQuery Question

serializing sortables not working

I've tried everything and it still fails! What's wrong with this code?!?! I wanted to get the serialized sortable, it's that simple but I've looked on SO and found snippets.. applied with my code and it still doesn't work. It makes no sense at all. I did look at possible errors (and yes, there's set_number as specified by jQuery doc)... but still nothing works.

<html>
<body>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'>
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js">
</script>
<script>

$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});

$("form").submit(function(){
$('#thedata').val($( "#sortable" ).sortable("serialize"));
return false;
});

</script>
<h1>
Filters For Tables
</h1>
<h2>
Filters for Assets
</h2>
<form action="validate.php" method="post">
<input type='text' name='thedata' id='thedata' />
<ul id="sortable">
<li id="foo_0">ID</li>
<li id="foo_1">TIME LOG</li>
<li id="foo_2">DEVICE TYPE</li>
<li id="foo_3">CHASSIS TYPE</li>
<li id="foo_4">PARENT ID</li>
<li id="foo_5">PARENT</li>
</ul>
<input type="submit" name="submit" id="submit" value="Update" />
</form>
</body>

</html>

Answer

The form element does not exist. You have to bind events when the DOM is ready. Just move this:

$("form").submit(function(){         
    $('#thedata').val($( "#sortable" ).sortable("serialize"));
    return false;        
});

To this function: $(function() {}); It works on JSFiddle because there is JavaScript called when the DOM is loaded I think.