json - jQuery set selected option from data on page load -
i have page uses jquery load option dropdown on page load. part works fine. want set selected option in dropdown baised on querystring if there 1 - , default if there not one. querystring being recovered fine can not setting of selected option work. in code below when stop @ "debugger" line , examine select0 undefined (after haveing been loaded successfully) if allow code keep running dropdown populated data ajax call. guessing why selected item not being set - can't figure out how 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); (var 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 querystring use $("#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 usa } } });
you're trying match text
attribute not exist. 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 library:
$("#select0 option").filter(function() { return $(this).text() == mytext; }).first().prop("selected", true);
Comments
Post a Comment