+ Start a Discussion
Robert WynterRobert Wynter 

JavaScript get selected index from dropdown

Using JS to add to a dropdown from Salesforce repeater prefills. This works great, however, when I try to get the selected value when a user selects from the dropdown (tfa_4) and add to a text box (tfa_25), I get undefined. I've tried .selectedIndex -1, +1 and just selectedIndex and sometimes it works but only on one or two selected values and not in the right order

 
<script type="text/javascript">
    
    
    window.onload = document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("tfa_4").options.length=0;
    var option = document.createElement("option");
    option.text = "Select Tour Date";
    document.getElementById("tfa_4").add(option);
    var startDate = document.querySelectorAll('[id^=tfa_9]');
    var campaignRepaterID = document.querySelectorAll('[id^=tfa_26]');
    
    for(var i in startDate){
                   textToWrite = startDate[i].value;
                if (textToWrite) {
                    if (textToWrite.length > 1) {
                        displayTime = textToWrite;
                        addToDropdown(displayTime);
                       }
                }
            }
            
    document.getElementById("tfa_4").addEventListener(
     'change',
  function getSelectedValue(){    //Gets the index value of the selected event
      var x = document.getElementById("tfa_4").selectedIndex - 1;
      //Finds and sets the event ID
var IDToFind = campaignRepaterID[x].value;
var dd = document.getElementById('tfa_25');
    dd.value = IDToFind;
    return;
        
}

  );
    
    });
    
    
    // Function to add to the campaign dropdown
        function addToDropdown(text) {
            var x = document.getElementById("tfa_4");//Dropdown field
            var option = document.createElement("option");
            option.text = text;
            x.add(option);
        }
        
</script>