miechooy
miechooy

Reputation: 3422

Show specific value in dropdown

I have a table where in each row for each id we have 'Client' column. When a user clicks on the row he is able to change client. I am using jquery.dialog for this operation. When a dialog appears the user sees a dropdownlist with Clients. How I can make that after dialog appears, the user sees the current client as the selected item in the dropdown? I've tried as below:

onDblClickRow: function (row, $element) {
    $.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
        if (clients.length == 0) {
            $('#clientNameEdit').empty();
            $('#clientNameEdit').append('<option value="0">Tasks</option>');
        }
        $.each(clients, function (index, clientt) {
            $('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
        });
    })
   var currentClient = row.clientName; // Client name from Row
   $('#clientNameEdit select').val(currentClient); // Tried to set like that 
}

but doesn't work

Upvotes: 1

Views: 83

Answers (2)

BenG
BenG

Reputation: 15154

The value passed in to .val needs to be the clientt.Value and not the text name.

if you dont have the clientt.Value, then try something like:-

$("#clientNameEdit option[text=" + currentClient + "]").attr("selected", true);

And bring the setting of the select inside of the success function.

Upvotes: 1

Jaco B
Jaco B

Reputation: 1043

The following alteration to your code snippet should do the trick:

onDblClickRow: function (row, $element) {
            $.getJSON('/ManageProjects/GetAvaibleClients/', function (clients) {
                if (clients.length == 0) {
                    $('#clientNameEdit').empty();
                    $('#clientNameEdit').append('<option value="0">Tasks</option>');
                }
                $.each(clients, function (index, clientt) {
                    $('#clientNameEdit').append("<option value='" + clientt.Value + "'>" + clientt.Text + "</option>");
                });
                var currentClient = row.clientName; // Client name from Row
                $('#clientNameEdit').val(currentClient); // Tried to set like that but doesn't work                
            });

As indicated above, if you do the currentClient = row.clientName outside the success of the ajax call, it will probably fire before the dropdown is populated and therefore not have any effect.

Secondly the jQuery selector '#clientNameEdit select' should only be '#clientNameEdit' as it refer to the dropdown itself and not it's parent.

Upvotes: 0

Related Questions