Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set selected option from data on page load

Tags:

json

jquery

I have a page that uses jQuery to load an option dropdown on page load. That part works fine. I then want to set the selected option in the dropdown baised on the querystring if there is one - and default it if there is not one. The querystring is being recovered fine but I can not get the setting of the selected option to work. In the code below when I stop at the "debugger" line and examine Select0 it is undefined (after haveing been loaded successfully) but if I allow the code to keep running the dropdown is populated with the data from the ajax call. I am guessing that this is why the selected item is not being set - just can't figure out how to resolve 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          
               }
           }
       });
like image 302
Jim Evans Avatar asked Dec 05 '25 11:12

Jim Evans


1 Answers

You're trying to match a text attribute that does not exist. You cannot write:

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

You can use filter() instead:

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

Or, taking more advantage of the library:

$("#Select0 option").filter(function() {
    return $(this).text() == myText;
}).first().prop("selected", true);
like image 126
Frédéric Hamidi Avatar answered Dec 07 '25 00:12

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!