MJ
asked on
Two Selects on one page with same class but one had ID, how to detect which one changed? ***Javascript Only Solution***
I currently have the following code which works for a single Select:
The issue is the webpage can have 2 locations where a user can change the select and they are named the same thing (same class). I can do this:
Thanks!
var sSel = document.getElementsByClassName("stateSelectorDropdown");
var selectedState = sSel[0].selectedIndex;
var currState = sSel[0].options[selectedState].text;
The issue is the webpage can have 2 locations where a user can change the select and they are named the same thing (same class). I can do this:
var sSel = document.getElementsByClassName("stateSelectorDropdown");
var selectedState = sSel[0].selectedIndex;
if(selectedState == 0){
selectedState = sSel[1].selectedIndex;
}
var currState = sSel[0].options[selectedState].text;
But this seems hokey! The first one on the page has an an id of stateSelector where the second one has no id. Is there a better way of detecting which select was changed? Javscript only solution please.Thanks!
Lets say that you have these select elements with the same class:
HTML:
Then you can bind an event listener with preventdefault method inside to avoid get value from the other select elm:
HTML:
<select name="" id="" class="stateSelectorDropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="" id="" class="stateSelectorDropdown">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
Then you can bind an event listener with preventdefault method inside to avoid get value from the other select elm:
(function (){
var sSel = document.getElementsByClassName("stateSelectorDropdown");
for(var i=0;i<sSel.length;i++){
sSel[i].addEventListener('change',function(e){
var selectedState=this.value;
console.log(selectedState);
e.preventDefault();
});
}
@Leonidas: You do not want to preventDefault on a select
Also document.querySelectorAll( ".stateSel ectorDropd own");
Also document.querySelectorAll(
ASKER
I can not touch the code on the page so I can't add another ID to the second select.
Thanks
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window
it is good to have unique ids, but you can leave it if you wish...
Open in new window
then anytime, use currState, it will have latest selected state...