Travis Travis - 1 month ago 17
Javascript Question

Opening link in new tab if Check box is checked Otherwise opening it on same page

<!DOCTYPE html>
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">


function OpenWindow(info) {
if
{
window.open(info,'WinName','height=400,width=600,resizable=yes,scrollbars=yes');
}
else
{
target="_self";
}
}
</script>
</head>
<body>
<p>
<input type="checkbox" name="CBox0" value="www.youtube.com" > Click To Open Link in New Window!</p>

<br>

<a href="http://www.youtube.com" target="new" id="y"onclick="if(this.checked){OpenWindow(this.value)}">Youtube</a>

</body>
</html>


This is what i have so far. When the check box is checked, if i click on a link, it will open the website up in a new tab. But if it is not checked, it opens up on the same page like a regular link. I have been working on this for awhile, so any help will be greatly appreciated. Thanks!

Answer

You had some markup issues and inline stuff that I've removed. This should do it for you: http://jsfiddle.net/L47NY/7/

<input id="checky" type="checkbox">Click To Open Link in New Window</input>
<br />
<a href="http://www.youtube.com" id="linky">Youtube</a>

var checky = document.getElementById('checky');
var anchor = document.getElementById('linky');
var link = anchor.getAttribute('href');

function OpenWindow(href) {
    if (checky.checked) {
        window.open(href, '_blank');
    } else {
        window.open(href, '_self');
    }
}
anchor.onclick = function () {
    OpenWindow(link);
    return false;
};