Create <option> on the fly with jQuery

I would like to build s on the fly in a box based on the AJAX answer; that is, if responseText is 3, I would like to build 3 options:

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

The following code snippet works:

$("#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 would like to "jQueryfy":

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

Larger, sometimes responseText is null (the page is empty), and parsing it gives, of course, "NaN": well, in this case I would like to fill out a simple one:

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

I am new to JS and don't know how to do this ... Please help?

+3
source share
1 answer

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.

+4
source

Source: https://habr.com/ru/post/1717047/


All Articles