Maxwell Donnelly Maxwell Donnelly - 3 months ago 11
HTML Question

Button href changed by select list won't resolve (javascript:window.open(window.variable))

I am using javascript to successfully change the href of a button based on the user's selection from a select list. However, the href value is a javascript variable, and it fails to resolve after it has been changed by my code.

Here is the code:



var clickTag1 = "http://www.myexampledomain.com/test-1";
var clickTag2 = "http://www.myexampledomain.com/test-2";
var clickTag3 = "http://www.myexampledomain.com/test-3";
var clickTag4 = "http://www.myexampledomain.com/test-4";

(function() {
var form = document.forms['swiftForm'];

//document.getElementById('cT_target').href = 'javascript:window.open(window.' + this.value + ')';
var trigger = document.getElementById('cT_toggle');
trigger.onchange = function() {

var link = document.getElementById('cT_target');
link.href = 'javascript:window.open(window.' + this.value + ')';
}
})();

<form id="swiftForm">
<div class="styledSelect">
<select name="cT_toggle" id="cT_toggle">
<option value="clicktag1">2 meters</option>
<option value="clicktag2">4 meters</option>
<option value="clicktag3">6 meters</option>
<option value="clicktag4">8 meters</option>
</select>
</div>
<div class="swiftSubmit">
<a id="cT_target" href="javascript:window.open(window.clickTag1)">Calculate</a>
</div>
</form>





Upon page load, the button href works as expected (opens a new window containing the destination clickTag URL). However, after the href is changed by selecting a new value from the select list, the href no longer opens the destination clickTag URL, but just opens an empty window.

The problem appears to be the fact that the javascript variable value (clickTag) is no longer evaluating after it has been changed in the on-page HTML.

I'm wondering if there is some trick I'm missing?

Answer

Javascript is case sensitive the value of select should match the name of the variable

Change

<select name="cT_toggle" id="cT_toggle">
    <option value="clicktag1">2 meters</option>
    <option value="clicktag2">4 meters</option>
    <option value="clicktag3">6 meters</option>
    <option value="clicktag4">8 meters</option>
</select>

To

<select name="cT_toggle" id="cT_toggle">
    <option value="clickTag1">2 meters</option>
    <option value="clickTag2">4 meters</option>
    <option value="clickTag3">6 meters</option>
    <option value="clickTag4">8 meters</option>
</select>