I have an issue getting some basic JavaScript running. I just recently started with JavaScript, so I haven't come close to fully grasping it yet. What I want to achieve is return the value of an option selector inside a div of a form/table.
I am utilzing Google Tag Manager to send data to Google Analytics and trying to use the built-in auto-event listeners along with custom JavaScript macros.
Basically, there are three different selectors that all have different values. These are all inside a table with selections in <select>
.
How could I use JavaScript to get the selected value from each of the three different selectors?
The issue I am struggling with is the fact that the selectors themselves have no ID to separate them apart, but the parent element atleast has a unique div id.
I'll try to give a visualization on how it looks:
<form>
<div id="selection1">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
<div id="selection2">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
<div id="selection3">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
</form>
How would I be able to retrieve the values from the different options and that are selected? I have tried this, and it works:
function () {
var option = document.GetElementsByTagName("select")[0].value;
return option;
}
But then I'd need to set this up for each of the three different selections you can choose something from. I am just not savvy enough to figure out how to write a JavaScript that can calculate what someone chose in the three different options and return its values.
Alright, first let's improve your code:
<option value="xy">This is some random text</option>
General approach:
var selects = document.getElementById("myselect");
var selectedValue = selects.options[selects.selectedIndex].value;// will gives u "xy"
var selectedText = selects.options[selects.selectedIndex].text;// gives u "This is some random text" but you should not use this<br><br>
You may want to use something like that:
var selects = document.querySelector("#selection1 select"); //This will return the first <select> inside the specified id. You may need to adjust that selector...
var selectedText = selects.options[selects.selectedIndex].text;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.