2015-06-30 2 views
5

Ich habe diese Funktion:Wie wird das erste Element aus der Dropdown-Liste bei Änderung gedruckt?

function LoadRegions() { 
    var region = $('#RegionID'); 


    var url = "/Account/GetRegions"; 
    $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) { 
     // clear and add default (null) option 

     //region.empty().append($('<option></option>').val('').text('Please select')); 



     for (var i = 0; i < response.length; i++) { 
      region.append($('<option></option>').val(response[i].Id).text(response[i].Name)); 
     } 

    }); 
} 

Wenn der Benutzer wählen countrie ich diese Funktion aufrufen, aber ich möchte auf anzuzeigen, aus dieser Liste erste Element zu starten ... Mit dieser Zeile i „Bitte wählen Sie“ erhalten, aber ich will erstes Element von Liste:

Wenn ich diese Zeile kommentiere, werde ich leer ... irgendeine Hilfe?

Antwort

2

Ich glaube, das Problem mit Verkettungs die Probleme haben könnte. Siehe Dokumentation für end().

Die empty() und append() wurden auf der gleichen Kette durchgeführt. Dies kann manchmal Probleme aufgrund des Verkettungsalgorithmus verursachen. Die documentation hat eine gute Beschreibung des Problems.

Dies kann Ihr Problem beheben.

$.getJSON(url, { 
    countryId: $('#CountryID').val() 
}, function(response) { 
    // clear and add default (null) option 
    region 
     .empty() 
     .end() 
     .append($('<option>', { 
      value: '', 
      text: 'Please select' 
     })); 
    $.each(response, function(key, tocken) { 
     region.append($('<option>', { 
      value: tocken["Id"], 
      text: tocken["Name"] 
     })); 
    }); 
}); 
0

Sie müssen das Attribut selected im Optionsfeld festlegen, um die Option als ausgewählt zu setzen. Um dies zu tun, müssen Sie Ihre for-Schleife wie folgt ändern:

for (var i = 0; i < response.length; i++) { 
    if(i==0) 
     region.append($('<option selected></option>').val(response[i].Id).text(response[i].Name)); 
    else 
     region.append($('<option></option>').val(response[i].Id).text(response[i].Name)); 
} 
0
var s_string = '<option>Select Value </option>'; 

for() // your for loop 
{ 
    s_string+=''; //your option tag code (appned fetch data in same variable and appned that variable after for loop end) 
} 

// appand s_string variable to your destination id or class (append) 
Verwandte Themen