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>
<html>
<head>
<script type="text/javascript">
function test1(){
if (window.location.indexOf('
alert('yes');
} else {
alert('no');
}
}
</script>
<body>
<a href="javascript:test1();"
Use window.location.href.index Of('http') instead.
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) {
if(window.location.indexOf
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>
<script type="text/javascript">
function test1(){
if (window.location.indexOf('
alert('yes');
} else {
alert('no');
}
}
</script>
<body>
<a href="#" onClick="test1(); return false">test</a>
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.inde xOf('foo.' )) {
alert('Hi, this is FOO.');
}
if (window.location.href.inde xOf('bar.' )) {
alert('Hi, this is BAR.');
}
}
</script>
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.inde
alert('Hi, this is FOO.');
}
if (window.location.href.inde
alert('Hi, this is BAR.');
}
}
</script>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.