selectedIndex is undefined

Discussion in 'JavaScript' started by gilgalbiblewheel, Jan 28, 2009.

  1. #1
    I'm getting:
    I don't know what's wrong with this:
    
    		<select id="book" size="5" onchange="fillChapters();" style="border: medium none ; margin: 5px 5px 0px; float: left; background-color: white; width: 190px;">
    			<option value="" style="background-color: rgb(181, 162, 111); color: white; font-weight: bold; font-style: italic;">Select Book</option>
    			<option value="1">Genesis</option>
    <option value="2">Exodus</option>
    <option value="3">Leviticus</option>
    <option value="4">Numbers</option>
    <option value="5">Deuteronomy</option>
    ...
    		</select>
    	
    Code (markup):
    function fillChapters(){
      var req = createRequest();
      if(req){
        req.onreadystatechange = function(){
          var c = document.getElementById('showchapterdiv');
          if(req.readyState){
    	if(req.readyState == 4){
    	  if(req.status == 200){
    	    c.innerHTML = req.responseText;
    	  }
    	}
          }
        }
        var bobj = document.getElementById('book');
        var book = bobj.options[bobj.selectedIndex].value;
    	
        req.open('GET','getChapters.php?book='+book,true);
        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        req.send(null);
      }
    }
    
    Code (markup):

     
    gilgalbiblewheel, Jan 28, 2009 IP
  2. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    looks like it can't find the book element.
    maybe you have two elements with id 'book' in your document?

    do alert(bobj) after the assignment and see what it echos
     
    yoavmatchulsky, Jan 28, 2009 IP
  3. gangadhar godse

    gangadhar godse Guest

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I think you are trying the call fillChapters() function on body load event. If that is the case, then there is a problem because On body load the value of bobj.selectedIndex will be -1. this is where the error occurs.

    try to put 'selected' attribute on one of the options like this.

    <option value="4" selected>Numbers</option>

    This should solve the issue.

    enjoy.

    Gangs
     
    gangadhar godse, Jan 29, 2009 IP