4

I have this HTML list

<ul id='usernameList'>
    <li class='username'>John</li>
    <li class='username'>Mark</li>
</ul>

and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names

[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]

I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/

This is my AJAX submit

var form = $('#formUsername');
form.submit(function () {
$.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize(),
    dataType: "json",
    beforeSend: function () {
        //
    },
    success: function (data) {

        var listUsernames = $('#usernameList');
        var numUsernames = listUsernames.children().length;

        $.each(data, function(i, user) {
            if(user.newUser == "yes"){

                var htmlUser = "<li class='username'>" + user.name + "</li>";
                var added = false;

                $(".username", listUsernames).each(function(){
                    if ($(this).text() > user.name) {
                        $(htmlUser).insertBefore($(this));
                        added = true;
                    }

                });

                if(!added)
                    $(htmlUser).appendTo($(listUsernames));

            }

            // HERE I DO alert('numUsernames')
            // I get the same number of users before sending form

            // How can I update here the value of listUsernames and numUsernames?
        });



    }
});
return false;
});

My question is, how I can update the value of listUsernames and numUsernames after adding an item?

4

3 に答える 3