tags:

views:

221

answers:

1

Hello, 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?

+3  A: 

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.

Paul Suart
1. You're missing a final `>` there.2. The reccomended form according to the jQuery docs is `$('<option/>')`, not `$('<option></option>')`. Doesn't matter if you're using XHTML or not, it's a hint to jQuery itself that you want to create a bare element.
hobbs
1. Thanks, amended. 2. I didn't know that btw :)
Paul Suart