Patrick Obafemi
Patrick Obafemi

Reputation: 1066

Append to data from ajax request

I have a function that makes a call to a server and appends the result(which is a list of names) to a select dropdown. Now I want to append a select name option to the resulting data. Here is my code

$('#state').on('change', function() {
                $.ajax({
                    type: 'GET',
                    url: '/get-names/' + this.value,
                    success: function(data) {
                        $('#names').empty();
                        $.each(data.names, function(key, value){
                            $('#names').append('<option value="'+value.name+'">'+value.name+'</option>');
                        });
                    }
                });
            })

The result gives me an array of objects

name: [{id: 119, manager_id: 7, name: "Sam"}, {id: 120, manager_id: 7, name: "Shreck"}]

How do I append the 'Select Name' option to the result?

Upvotes: 0

Views: 761

Answers (3)

Maxim Zaytsev
Maxim Zaytsev

Reputation: 43

$('#state').on('change', function() {
    $.ajax({
        type: 'GET',
        url: '/get-names/' + this.value,
        success: function(data) {
            $('#names').html('<option value="" selected>Select Name</option>');
            $.each(data.names, function(key, value){
                $('#names').append('<option value="'+value.name+'">'+value.name+'</option>');
            });
        }
    });
});

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89179

Just append it before the each loop.

$('#names').empty();
$('#names').append('<option value="Select Name">Select Name</option>');
$.each(data.names, function(key, value){
   $('#names').append('<option value="'+value.name+'">'+value.name+'</option>');
});

Upvotes: 1

Phil Golding
Phil Golding

Reputation: 471

If you want it at the top of the list - just use unshift to place the text at the start of the array:

success: function(data) {
                        $('#names').empty();
                        data.names.unshift("Select Name");
                        $.each(data.names, function(key, value){
                            $('#names').append('<option value="'+value.name+'">'+value.name+'</option>');
                        });
                    }

Upvotes: 0

Related Questions