I have an HTML form with a simple JavaScript function that is meant to send the user to a different link based on the option selected.
<form>
<select name="deliveryType">
<option value="123">Item 1</option>
<option value="456">Item 2</option>
<option value="789">Item 3</option>
</select>
<p><a href="javascript:void(0);" onClick="javascript:addToCart(this);">Submit</a>
<script>
function addToCart(t) {
var dT = t.parentNode.parentNode.childNodes[1].value;
alert(dT);
// location.href = "http://linkprefix.com/?variable=" + dT;
}</script>
</form>
It works as expected. The variable dT
returns the value of the selected option.
However, if there is no line break between <form>
and <select>
, dT
returns undefined
. But then if I change childNodes[1]
to childNodes[0]
it then works again. I don't know why this would happen. I thought parentNode
and childNode
were based on HTML elements and the text within them, not line breaks between elements. If I had to guess, the line break is being counted as a text node, but that makes no sense to me. Is that what's happening? Is there a better way to do this?
` but also by `\n` ( newline characters), so that can be one reason for this to make sencse and keep newlines as Text note inside the `childNodes` array – Alon Eitan Aug 20 '17 at 17:18