Search code examples
javascripthrefwindow.open

Open page in new tab using javascript window.open(elementName.elementValue) in anchor tag


I've examined tons of examples over the past couple days, but still can't find an answer to my dilemma. In order for me to explain my dilemma first I'll show you an example of something I have that works, then explain how I would rather it work (but can't seem to achieve).

This works:

<form>
<select name="url">
    <option selected="selected" value=""> Choose Donation Amount </option>
    <option value="http://www.url1.com">URL#1</option>
    <option value="http://www.url2.com">URL#2</option>
    <option value="http://www.url3.com">URL#3</option>
    <option value="http://www.url4.com">URL#4</option>
    <option value="http://www.url5.com">URL#5</option>
    <option value="http://www.url6.com">URL#6</option>
</select>
<input type="submit" value="Submit" onclick="if (url.value) window.open(url.value);" />
</form>

But what I'd rather do is capture the option and open the URL using an anchor tag (rather than input[type"submit"]), something like this (to replace the input tag before the closing form tag):

<a href="javascript:void(if (url.value) window.open(url.value));" target="_blank">Submit</a>

The above line doesn't work, and I can't figure out how to form it correctly. Help?

I know this doesn't seem logical, especially since I already have it working using a submit button, but it's also not practical for me to explain exactly why I don't want to use input or button type="submit", , or PHP. Please, it really needs to be inline javascript in an anchor tag. Thanks.s :-)


Solution

  • Add your form name attribute like:

    <form name="form">
    

    ... and then try it like that:

    <a href="" onclick="window.open( form.url.value, 'windowName' ); return false" target="_blank">Submit</a>
    

    There is a working example.