如何在更改时从下拉列表中打印第一个元素?

时间:2015-06-30 09:17:47

标签: javascript jquery

我有这个功能:

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));
        }

    });
}

当用户选择countrie我调用此函数但我想在该列表的开始第一个元素上显示... 有了这一行,我得到“请选择”,但我想要列表中的第一个元素:

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

如果我对此行发表评论,我会感到空白......有任何帮助吗?

3 个答案:

答案 0 :(得分:2)

我认为问题可能是链接问题。请参阅 end() 的文档。

empty()append()正在同一条链上完成。由于链接算法,这有时会导致问题。 documentation 对此问题有很好的描述。

这可以解决您的问题。

$.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"]
        }));
    });
});

答案 1 :(得分:0)

您需要在选项标记中设置属性selected,以便将选项设置为已选中。为此,您需要像这样修改for循环:

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));
}

答案 2 :(得分: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)