Go to different url on clicking button

Sangram Nandkhile picture Sangram Nandkhile · Jun 17, 2011 · Viewed 40.1k times · Source

i need to create html code, in which if user selects an item from drop down list and click button then it will go to respective link.

<select name="myList">
<option value="Google" />Google
<option value="yahoo" />yahoo
<option value="Ask" />Ask
</select>

if user selects Google from drop down list and clicks button, then page should be redirected to www.google.com and if it selects yahoo and clicks button should go to www.yahoo.com

I would like to mention that I need The button in this scenario. I don't want to go respective site on drop down selection.Only after clicking the button.

Thank you in advance.

Answer

James Hill picture James Hill · Jun 17, 2011

HTML:

<select name="myList" id="ddlMyList">
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
    <option value="http://www.ask.com">Ask</option>
</select>

<input type="button" value="Go To Site!" onclick="NavigateToSite()" />

JavaScript:

function NavigateToSite(){
    var ddl = document.getElementById("ddlMyList");
    var selectedVal = ddl.options[ddl.selectedIndex].value;

    window.location = selectedVal;
}

You could also open the site in a new window by doing this:

function NavigateToSite(){
    var ddl = document.getElementById("ddlMyList");
    var selectedVal = ddl.options[ddl.selectedIndex].value;

    window.open(selectedVal)
}

As a side note, your option tags are not properly formatted. You should never use the <... /> shortcut when a tag contains content.