JQuery sets selected option from page load data

I have a page that uses jQuery to load a dropdown of options on page load. This part works great. Then I want to set the selected option in the dropdown depending on the query string if there is one, and defaults to that if there is none. The recovery vertex is recovering, but I am unable to tweak the setting of the selected option. In the code below, when I stop at the "debugger" line and check Select0, it is undefined (after it has been loaded successfully), but if I let the code continue running, the dropdown is filled with data from the ajax call. I'm guessing this is why the selected item isn't set - just can't figure out how to solve it.

    $(document).ready(function () {
    $.ajax({
           type: "POST",
           url: "myPage.aspx/MyWebMethod",
           contentType: "application/json; charset=utf-8",
           data: "{}",
           dataType: "json",
           success: function (states) {
               var jsonCodes = JSON.parse(states.d);
               for (var i in jsonCodes) {
                   $("#Select0").append(new Option(jsonCodes[i].regionname, jsonCodes[i].region_id));
               }
               var first = getUrlVars()["region"];
               if (first) {
                   $.fn.GetInventory(1, 10, reg, 'rank', 'asc'); // If there is a querystring use it
                   $("#Select0 option[text='" + reg + "']").get(0).selected = true;
               }
               else {
                    debugger;
                   var myText = 'United States';
                   $("#Select0 option[text='" + myText + "']").get(0).selected = true;
                   $.fn.GetInventory(1, 10, 'United States', 'rank', 'asc'); // If no query string default to USA          
               }
           }
       });

      

+3


source to share


2 answers


You are trying to match an attribute text

that does not exist. You cannot write:

$("#Select0 option[text='" + myText + "']").get(0).selected = true;

      

Instead of filter () you can use



$("#Select0 option").filter(function() {
    return $(this).text() == myText;
}).get(0).selected = true;

      

Or, using more of the library's benefits:

$("#Select0 option").filter(function() {
    return $(this).text() == myText;
}).first().prop("selected", true);

      

+4


source


There are two errors in the code.

$("Select0 option[text='" + reg + "']").get(0).selected = true;

      

This is not true. Change to ->

$("#Select0 option[text='" + reg + "']").get(0).selected = true; 

      

Also:



$("Select0 option[text='" + myText + "']").get(0).selected = true;

      

This is not true. Change to:

$("#Select0 option[text='" + myText + "']").get(0).selected = true;

      

Must work.

0


source







All Articles