简体   繁体   中英

Looping through a ASP.NET Listbox with Javascript not working

I'm trying to loop through an ASP.NET listbox with Javascript, but I'm getting a null object or undefined when it hits the lboxRight variable in the for loop. Here's what I have.

function save() {
  var containsTypeA = false;
  var containsTypeB = false;
  var containsType = false;
  var lboxRight = $get('<%=lboxRight.ClientID %>').value;

  if (lboxRight != null) {
    for (var i = 0; i < lboxRight.options.length; ++i) {
      if (lboxRight.options[i].value == "Type A") {
        containsTypeA = true;
      }
      if (lboxRight.options[i].value == "Type B") {
         containsTybeB = true;
      }
    }
    containsType = true;
  }
}

There's an onclick event mapped to when the save button is pressed that calls this function. Am I doing this the right way to look at the listbox and tell me if it has this specific value in it? My intention is for the listbox to contain Type A as a value and then when it loops through the listbox, if it finds that value within the list it will set that variable to true for some other logic. Visual Studio seems to complain about the for loop line, what am I doing wrong here? I am using the exact same loop written elsewhere and it works fine, so I am not understanding why this one isn't working.

Is there anything wrong with this as I have written it?

If it is complaining about something being null or undefined on the for loop line I would check to see what lboxRight.options is since you already check lboxRight.

Actually it wouldn't make sense for options to exist since lboxRight is being set to the value of the select not the select.

Try changing

var lboxRight = $get('<%=lboxRight.ClientID %>').value;

to

var lboxRight = $get('<%=lboxRight.ClientID %>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM