Jim Jim - 4 months ago 28
jQuery Question

JQuery Selector not working, where looping does. Why?

I have two jquery selectors that I used which did not find the desired option where the third "brute force" method did. I am at a complete loss as to why. Each looked like they should of and I validated the document was fully loaded when the selector ran. I tried each with value and text in the selector and got the same result in my page. The html is dynamically loaded using the jquery load method below (where theType is a value coming from a html select control) as well as the associated javascript:

var theType = $('#TicketType option:selected').val();
var theId = $("#Id").val();
var url = '/SystemBuildSiteConfigs/' + theType + '/' + theId;

$('#ticketDiv').html("");

$("#ticketDiv").load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error loading the " + theType + " form");
}
else {
$.getScript("/Scripts/SiteConfig" + theType + ".js", function () {
});
}
});


The html select in question:

<select name="SupportOrganization" class="form-control" id="SupportOrganization">
<option value="">- Please Select -</option>
<option>Auxiliary IT</option>
<option>Business Intelligence</option>
<option>Change Management</option>
<option>Engineering RnD</option>
<option>Enterprise Business Solutions</option>
<option>Enterprise Solutions</option>
<option selected="selected">Hosting</option>
<option>Infrastructure and Operations</option>
<option>Manufacturing</option>
<option>Professional</option>
<option>Support</option>
</select>


First selector statement:

$("#SupportOrganization").find('option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);


Second selector statement:

$('#SupportOrganization option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);


What worked:

$('#SupportOrganization option').each(function (idx, ele) {
if ($(ele).val() == jsonObj.SupportOrganization)
$(ele).attr("selected", true);
});


The page segment loads correctly and all the other javascript that fires to load html controls with content are executing as expected. Another page type loads and fires correctly performing similar functions. Using jsfiddle, both selectors show they work correctly. What I found through testing was


  • The variable did have the expected value.

  • The text selector did not work correctly on my page

  • The value selector did select an object. However I was unable to determine what the object was and the attr() method did not set the target attribute value.



I can go with what I found that will work, just wanted to find out why this wouldn't work. Guessing it has something to do with the dynamically loaded html and javascript?

Answer

The jQuery .val() function uses a "hook" for <option> elements to return the text content of the element if the "value" attribute is missing. Your <option> elements don't have "value" attributes, so the selector does not match.

Comments