简体   繁体   中英

onclick redirect to different url

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>

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/

Why?

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 0 th 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.

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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM