Reputation: 402
I am creating a pulldown menu that pushes the user to a selected url. In the list i have several values that are set at 0 which i use for headers in the list. I have set them to 0 so they do nothing.
This works for the first one in the list which has a value of 0 but the others that do have a value of 0 still redirects the browser to a new website with the same domain and /0 at the end? What am i missing?
<select onchange="if (this.selectedIndex > 0) document.location.href=this.value;">
<option value="0" selected="selected">More...</option>
<option value="0">----- Locations -----</option>
<option value="http://www.location1.com/">location1</option>
<option value="http://www.location2.com/">location2</option>
<option value="http://www.location3.com/">location3</option>
<option value="0">----- Other Locations -----</option>
<option value="http://www.olocation1.com/">olocation1</option>
<option value="http://www.olocation2.com/">olocation2</option>
<option value="http://www.olocation3.com/">olocation3</option>
</select>
Upvotes: 1
Views: 8305
Reputation: 7018
change your code to:
<select onchange="if (this[this.selectedIndex].value !== '0') document.location.href=this.value;">
<option value="0" selected="selected">More...</option>
<option value="0">----- Locations -----</option>
<option value="http://www.location1.com/">location1</option>
<option value="http://www.location2.com/">location2</option>
<option value="http://www.location3.com/">location3</option>
<option value="0">----- Other Locations -----</option>
<option value="http://www.olocation1.com/">olocation1</option>
<option value="http://www.olocation2.com/">olocation2</option>
<option value="http://www.olocation3.com/">olocation3</option>
</select>
demo: http://jsfiddle.net/pratik136/kWHXX/
Your code:
onchange="if (this.selectedIndex > 0) document.location.href=this.value;"
was checking for the index
of the selected option
in the list. Now because list indices start from 0
, you were getting expected results when the first (or 0th index) item was selected. But all other items passed the selectedIndex > 0
test and got redirected.
using
onchange="if (this[this.selectedIndex].value !== '0') document.location.href=this.value;"
basically checks for the value
of the selected index
, and if the value !== '0'
, it redirects to it.
Upvotes: 4
Reputation: 9850
You're redirecting them to the url 0
, which it interprets as /0
. You probably want to do a check to make sure that the value is not "0"
, by using something like this.value !== "0"
.
Upvotes: 3