Phill Greggan
Phill Greggan

Reputation: 2394

How do i set the select value of a drop down?

i have the following code to load a dropdownlist with json data

    $('#btnAddNew').click(function (evt) {

        $.ajax({

            url: '@Url.Action("GetAllEmployee","Employee")',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                //edit form's ddl 
                $('#ddlEmployeeCategories').empty();
                console.log(data);
                $(data).each(function (index, item) {
                    //edit forms ddl
                    $('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
                });
            },
            error: function () { }
        });



        $('#empID').val('');
        $('#ddlEmployeeCategories').val('2');
        $('#txtFirstName').val('');
        $('#txtLastName').val('');
        $('#txtDOB').val('');
        $('#txtSalary').val('');
        $('#cbIsMarried').prop('checked', false);


        form.dialog('open');

        resetValidations();
        form.show();          

    });

the line $('#ddlEmployeeCategories').val('2'); set the selected item to the item of value '2' (NOT the INDEX). but this does not set selected item. why?

Upvotes: 0

Views: 716

Answers (2)

Saqib Amin
Saqib Amin

Reputation: 1171

Modify the values after ajax call returns success:

$('#btnAddNew').click(function(evt) {

    $.ajax({

        url: '@Url.Action("GetAllEmployee","Employee")',
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            //edit form's ddl 
            $('#ddlEmployeeCategories').empty();
            console.log(data);
            $(data).each(function(index, item) {
                //edit forms ddl
                $('#ddlEmployeeCategories').append($('<option/>', {
                    text: item.Description,
                    value: item.ID
                }));
            });

            $('#empID').val('');
            $('#ddlEmployeeCategories').val('2');
            $('#txtFirstName').val('');
            $('#txtLastName').val('');
            $('#txtDOB').val('');
            $('#txtSalary').val('');
            $('#cbIsMarried').prop('checked', false);


            form.dialog('open');

            resetValidations();
            form.show();
        },
        error: function() {}
    });


});

Upvotes: 1

Change your success to:

success: function (data) {
  $('#ddlEmployeeCategories').empty();
  $(data).each(function (index, item) {
    $('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
  });
  $('#ddlEmployeeCategories').val('2');
  ... // your other code
}

You must set that item when you are certain that your ajax call has finished.

Upvotes: 1

Related Questions