Javascript - Return value of current page name?

Soldato
Joined
18 Oct 2002
Posts
3,245
Location
melbourne
Hi folks,

How can I get javascript to return the current filename of the web page?

Hi have three pages and I want to run a script depending on what the current page is.

Example:

IF pagename = index.php?catId=1 THEN something
IF pagename = index.php?catId=2 THEN something else

I can't do this in PHP, it has to be javascript.

I'd appreciate any pointers.

Thanks.
 
I've found something which should do the trick

Code:
<script language="JavaScript">
<!--
// Create variable is_input to see if there is a ? in the url
var is_input = document.URL.indexOf('?');

// Check the position of the ? in the url
if (is_input != -1)
{ 
// Create variable from ? in the url to the end of the string
addr_str = document.URL.substring(is_input+1, document.URL.length);

// Loop through the url and write out values found
// or a line break to seperate values by the &
for (count = 0; count < addr_str.length; count++) 
{

if (addr_str.charAt(count) == "&") 
// Write a line break for each & found
{document.write ("<br>");}

else 
// Write the part of the url 
{document.write (addr_str.charAt(count));}

}}

// If there is no ? in the url state no values found
else
{document.write("No values detected");}

-->
</script>
 
I'll write you out a script specific to what you want :)

The one you found is used for multiple query string values (ie. page.html?id=3&qs=5&view=1000) and is not very cross browser.

Code:
<script>

//this section of code takes the value in the URL and
//inserts it into the variable 'cat_id'

var cat_id; //initialise
var curr_loc=document.location.href;
if (curr_loc.indexOf("?") != -1) {
var spar1=curr_loc.split("?");
var spar2=spar1[1].split("=");
cat_id=spar2[1];
} else {
alert("No query string value found!");
}

// just a test function here to make sure it works

function checkId() {
if (cat_id==1) {
alert("do whatever when cat id is 1"); // EDIT THIS LINE
} else if (cat_id==2) {
alert("do whatever when cat id is 2"); // EDIT THIS LINE
} else {
alert("Unknown cat ID"); // ERROR CATCH
}
</script>

The function will run and set the javascript variable 'cat_id' to the value supplied in the URL.

You can then do whatever you want with that. Delete the function I wrote called checkId() completely if you like, it's only there as a test.

Jon
 
Morlan said:
I can't do this in PHP, it has to be javascript.

seems odd as you're using php pages? can't you do the "if page = " bit in php and echo the javascript you want to run if the condition is met? :)
 
Back
Top Bottom