Create <option> on the fly with jQuery

帅比萌擦擦* 提交于 2019-12-04 04:33:26

问题


I'd like to build s on the fly in a box based on an AJAX response; i.e. if the responseText is 3, I'd like to build 3 options:

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>

The following piece of code is working:

$("#PAG_PLACEMENT").change(function(){
            $.ajax({
            type: "post",
            url: "untitled.asp",
            data: "iLanguage=1&iPlacement="+$("#PAG_PLACEMENT").val(),
            success: function(responseText){
                    //alert(parseInt(responseText));
                    opts = parseInt(responseText);
                            var routeSelect = $("#PAG_POSITION").get(0);
                            routeSelect.options.length = 0; //reset to zero length
                            for(var i = 0; i < opts; ++i) {
                            routeSelect.options[i] = new Option(i+1,i+1);
                            }
                    }
            });
    });

but I'd like to "jQueryfy" the part:

var routeSelect = $("#PAG_POSITION").get(0);
    routeSelect.options.length = 0; //reset to zero length
    for(var i = 0; i < opts; ++i) {
    routeSelect.options[i] = new Option(i+1,i+1);
}

More, sometimes the responseText is null (the page is blank) and parsing it gives of course a "NaN": well, in this case I'd like to fill the with a simple:

<option value="0">0<value>

I'm a JS newbie and don't know how to do this... Please, can you help?


回答1:


You can do:

var routeSelect = $("#PAG_POSITION").get(0);

routeSelect.html(''); //clear-out options

if (isNaN(opts) || opts == 0) {
    //Handles case where your response is invalid or zero
    routeSelect.append($('<option/>').val(0).html(0));
} else {
    //Add n items to the dropdown
    for(var i = 0; i < opts; ++i) {
        routeSelect.append($('<option/>').val(i).html(i));
    }
}

Hope this helps.



来源:https://stackoverflow.com/questions/1388302/create-option-on-the-fly-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!