简体   繁体   中英

Trouble using JavaScript dropdown more than once on the same page

I'm using this code for a drop down function in a table, and it's working great. However, when I try to use it more than once on the same page, One is corrupting the information of the other. I've tried changing the id settings but it didn't work. What do I need to do to so I can use this multiple time on a singe page. I'm using Wordpress and placing the script in the header.

<script language="JavaScript" type="text/javascript">
<!--
function openPop(){
    var Sel_Ind = document.getElementById('myURLs').selectedIndex;
    var popUrl = document.getElementById('myURLs').options[Sel_Ind].value;
    winpops=window.open(popUrl,"","width=400,height=338,resizable,")
}
//-->
</script>
</head>
<body>
    <select id="myURLs" onChange="javascript:openPop();">
        <option value="">Select a page...</option>
        <option value="http://news.bbc.co.uk">News</option>
        <option value="http://www.the-company.com">Music</option>
        <option value="http://www.b3ta.com">Laughs</option>
        <option value="http://www.google.com">Search</option>
        <option value="http://www.sitepoint.com/forums">Help</option>
    </select>

I think that's because you have hardcoded ids inside the onChange handler. Instead, what you can do is to pass the select element of which the onChange event fires into the handler function and use that to further processing.

<select id="myURLs1" onChange="openPop(this)">
    <option value="">Select a page...</option>
    <option value="http://news.bbc.co.uk">News</option>
    <option value="http://www.the-company.com">Music</option>
    <option value="http://www.b3ta.com">Laughs</option>
    <option value="http://www.google.com">Search</option>
    <option value="http://www.sitepoint.com/forums">Help</option>
</select>

<select id="myURLs2" onChange="openPop(this)">
    <option value="">Select a page...</option>
    <option value="http://news.bbc.co.uk">News</option>
    <option value="http://www.the-company.com">Music</option>
    <option value="http://www.b3ta.com">Laughs</option>
    <option value="http://www.google.com">Search</option>
    <option value="http://www.sitepoint.com/forums">Help</option>
</select>

Then in the handler function accept the select box into a parameter.

function openPop(sel){
    var popUrl = sel.options[sel.selectedIndex].value;
    winpops=window.open(popUrl,"","width=400,height=338,resizable,")
};

This way, you can have as many as select boxes you want and handler will behave correctly.

Check this fiddle for this implementation.

http://jsfiddle.net/BuddhiP/awc6o9ju/

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