Forum Moderators: open

Message Too Old, No Replies

Simple JavaScript Code

Help Please..

         

emoshe

10:30 am on Apr 9, 2006 (gmt 0)

10+ Year Member



Hi All,

I have this simple JavaScript code that takes the variable "key" from the url and print it somewhere in the page. I want to change it so if there is no variable key supplied, it will print a default value I will specify. As I have no idea in JavaScript coding, I'll appreciate if someone can help me with this. Here is the code:


<script language="JavaScript">
<!--
// Get the value of the variable "key" and print
addr_str = document.URL.substring(document.URL.indexOf('?key=')+5, document.URL.length);
document.write(addr_str.replace(/\+/gi, ' '));
-->
</script>

Thank you,
Eyal

Mohsen

11:57 am on Apr 9, 2006 (gmt 0)

10+ Year Member



"?key" may not be correct. You should check both "&key=" and "?key=".
Here is the correct code:

if (document.URL.indexOf('?key=')!= -1)
addr_str=document.URL.substring(document.URL.indexOf('?key=')+5, document.URL.length);
else if (document.URL.indexOf('&key=')!= -1)
addr_str=document.URL.substring(document.URL.indexOf('&key=')+5, document.URL.length);
else
{
// parameter does not exists
// do somthing
}

emoshe

1:08 pm on Apr 9, 2006 (gmt 0)

10+ Year Member



Thank you very much Moshen - it works perfectly!