Melanie
Melanie

Reputation: 3111

Javascript element with no id

I have a client-side javascript function on an ASP.Net page that's giving me fits. It's supposed to loop through the rows of a gridview, and through the controls on each row. It's finding a dropdownlist called ddlRole as it should, but then ddlRole doesn't seem to have an id property. ?? Here's the code:

 var gridID = '<%= gvMultiTimekeepers.ClientID %>';
    gridview = document.getElementById(gridID);
    for (var i = 0, row; row = gridview.rows[i]; i++) {
        var controls = row.getElementsByTagName("*");
        for (var j = 0; j < controls.length; j++) {
            var role = "";
            if (controls[j].id.indexOf("ddlRole") || controls[j].id.indexOf("ddlNewRole")) {
                alert("ddlRole id = " + controls[j].id);
                var ddlRole = controls[j];
                role = ddlRole.options[ddlRole.selectedIndex].value;
            }
        }
   }

So the code correctly finds the ddlRole using controls[j].id.indexOf but when the alert fires, it shows controls[j].id is blank. How is this possible? (I'm doing this alert because when I get to the assignment of the role variable two lines down, I'm getting an undefined or null reference error message.)

Upvotes: 1

Views: 98

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65825

You should be checking indexOf() against >-1 as in:

if (controls[j].id.indexOf("ddlRole") > -1 || controls[j].id.indexOf("ddlNewRole") > -1) 

since -1 is what indexOf() returns when no match is found.

In your scenario when the id isn't found, you are incorrectly entering the true branch of your if statement (a false positive) and if the match is found at index 0, your code will give you a false negative since 0 converts to a "falsey" value.

Upvotes: 1

Related Questions