I had a headache debugging the following code :
Presentation
If I run the following code :
$.get('/api/Customer/1', function(data){
    projects = data.data.projects;
    var $el = $('#mySelect');
    $el.empty();
    projects.forEach(function(element, index, array){
        var text = element.name;
        addSelectOption("mySelect", element.idProject, text);
    });
});
/**
 * Function which add an option to the select input which id is idSelect.
 */
function addSelectOption(idSelect, value, text)
{
    var option =
            $('<option></option>').attr("value", value).text(text);
    $('#' + idSelect).append(option);
}
My select will look like :
<select id="mySelect">
    <option value="1">proj1</option>
    <option value="2">proj2</option>
    <option value="3">proj3</option>
    <option value="4">proj4</option>
</select>
Failure
So, if I append the following line after my ajax code :
$('#mySelect').val("2");
My select should display proj2. But it doesn't.
Success
The only way I found to make it work is the following code :
$.get('/api/Customer/1', function(data){
    projects = data.data.projects;
    var $el = $('#mySelect');
    $el.empty();
    projects.forEach(function(element, index, array){
        var text = element.name;
        addSelectOption("mySelect", element.idProject, text);
    });
    $('#mySelect').val("2");//the only change between the presentation code
});
It looks like the html generated by jquery has a scope which is the get ajax request.
Question
I don't understand why the first code fail to set the selected value of mySelect to proj2. Can you explain it to me please ?
 
     
    