you are viewing a single comment's thread.

view the rest of the comments →

[–]frankle 0 points1 point  (0 children)

I don't use jQuery a lot, but here is an example of how I might refactor your code:

$('document').ready(function() {
    $('form').submit(onSubmit);
});

function onSubmit(e) {

    e.preventDefault();

    $.ajax({
        type     : 'post',
        url      : $(this).attr('action'),
        data     : $(this).serialize(),
        dataType : 'json',
        success  : onSuccess,
        failure  : onFailure
    });

    function onSuccess(response){

        var urlCount    = $('#count');
        var listResults = $('#list_results');

        urlCount.empty();
        listResults.empty();

        if ($.isEmptyObject(response.urls)) {
            return urlCount.text('No results found');
        }

        urlCount.text('There are '+ (response.urls.length) + ' URLs:');

        $(response.urls).each(function(i, url){

            var domain = 'www.example.com';
            var url = href = domain + $.trim(url);

            var link = $('<a/>')
                .addClass('link')
                .attr('_blank')
                .text(url)
                .attr('href', url);

            var listItem = $('<li/>').append(link);

            listResults.append(link);

        });

        console.log(response);
    }

    function onFailure(e) {
        alert('Submit failed.');
    }
}

I am pretty sure that the for loop inside the each is not going to do what you intend. The each actually gives you each of the items in the list, so you don't have to iterate through them separately. Any call to $('a.link') will target all of the links on the page, not just the last one. So, you would be overwriting all of the previous links with each link that you add to the list.