Вопрос

I have an input box for users to type in an item and then click the submit button or enter key and it is added to an unordered list with an id of sortable. I would like to make this user generated unordered list sortable using jQuery but I can't get it to work. I believe it involves the use of the on method but my attempts thus far have been completely unsuccessful.

Here is the link to the jsfiddle containing the project.

Also, here is what I am linking to in the head of the html file:

<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>

Edit: On jsfiddle the list items are sortable but the enter key can't be used to submit and [object Object] is outputted rather than the input text. When opening the file in browser (chrome) it still is not sortable but the added list items do have the proper outputs.

Это было полезно?

Решение

You would just need to write $('#listWish').val() instead of $('#listWish').

$("#submitButton").on("click", function(){
   $("#sortable").append('<li>' + $('#listWish').val() + '</li>').sortable("refresh");
});

Notice that I'm calling 'refresh' method after adding new item istead of reinializing whole list. For more information read here.

UPDATE: It could be the case when you call $("#sortable").sortable(); before your markup has been loaded. Try to make it this way:

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

All code inside $(function(){ }) wrapper will be called after all document is loaded.

Другие советы

This would be better if you do something like this

var changeText2 = function (){

    var listWish = $("#listWish").val();
    var node = $("#sortable").append("<li>")
    $("#sortable li:last-child").text(listWish);
    $("#sortable li").sort(naturalsort).appendTo("#sortable");

}

On JQuery .append() append a child node to the selection and .appendTo() append the selection contains, as child node, to an specific selection.

You can pass a function to the .sort() to specify how to sort the elements too.

Check my JSFiddle here

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top