0

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert

<!DOCTYPE html> 

<html>
  <head>
    <title>TEST</title>



    <!-- Javascripts -->
    <script type="text/javascript">
    var pageCount = 40; /*Total number of pages */
    var p;  /*Variable passed to go to a specific page*/

    function pageLoad(){ /*Loads in the pages as images */

        for( i = 1; i<= pageCount; i++){
            if(i < 10){
                i = "0"+i;
            }

            document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
            if( i == pageCount){
                gotoPage(p);
            }
        }       
    }

    function gotoPage(pageNum){  /* Moves webpage to target page of the PI */
        window.location = ("#page" + pageNum);
        alert(p);

    }


    function Test(){    
        window.open("./PI.html?p=15","new_pop");
    }

    </script>     
  </head>




  <body onload="pageLoad()">

  <div class="ExtBtn" onClick="Test()">
    <img alt="Exit" src="design/exit_btn-02.png" />
  </div> 



  </body>

</html> 

The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?

saq
  • 15
  • 2
  • I don't see any variable named `page` in your code. – Evan Davis Nov 09 '12 at 20:49
  • Here is a helpful function for URL-Parameter parsing http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values?page=1&tab=votes#tab-top – matz3 Nov 09 '12 at 20:52

3 Answers3

0

Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.

Use the function here: How can I get query string values in JavaScript? to get the value.

Also why are you checking for the last index, set the go to call after the for loop.

Community
  • 1
  • 1
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • The goTo was inside the loop because before, when my code was erroneous, it wasn't reading correctly outside (just changed it back). Anyway, thank to everyone here, this was a huge help. – saq Nov 09 '12 at 21:14
0

Here is your code with the correct alert(p) working: http://js.do/rsiqueira/read-param?p=15

I added a "function get_url_param" to parse url and read the value of "?p=15".