Link to home
Start Free TrialLog in
Avatar of qwertq
qwertq

asked on

indexOf with window.location not working

Why is this not working?

<html>
<head>

<script type="text/javascript">
      function test1(){
            if (window.location.indexOf('http')) {
                  alert('yes');
            } else {
                  alert('no');
            }
      }
</script>
<body>

<a href="javascript:test1();">test</a>
Avatar of TimCottee
TimCottee
Flag of United Kingdom of Great Britain and Northern Ireland image

Use window.location.href.indexOf('http') instead.
Avatar of stanscott2
stanscott2

Where the "http" is at the beginning of the string, indexOf returns 0.  In the IF test, 0 is treated as false.  Change it to this:

if(window.location.indexOf('http') > -1) {
Avatar of Michel Plungjan
Actually you want

<script type="text/javascript">
function test1(){
  if (window.location.indexOf('http')==0) { // see if the location STARTS with http
    alert('yes');
  } else {
    alert('no');
  }
}
</script>
<body>

<a href="#" onClick="test1(); return false">test</a>
Avatar of qwertq

ASKER

The solution I accepted is not working. This is _always_ alerting both the if.
The url does not start with the value, so I am not testing for -1 or == 0

<script type="text/javascript">
      function test1(){
            if (window.location.href.indexOf('foo.')) {
                  alert('Hi, this is FOO.');
            }
            if (window.location.href.indexOf('bar.')) {
                  alert('Hi, this is BAR.');
            }

      }
</script>
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial