0

I'm curious as to if it is possible to get this selector value after the user selects a value?

 <select>
   <option>test1</option>
   <option>test2</option>
 </select>

 //Idea of what i'm trying to accomplish
 select.addEventListener('select',()=>{
     console.log(select.value);
 })

I'm trying to use this value data to determine which item to load and view before you submit the form.

StarScream
  • 49
  • 7
  • 2
    ```select.addEventListener('change'``` – Rayon Aug 25 '22 at 14:25
  • you need to get the element of your selector first. Otherwise select is undefined – Chris G Aug 25 '22 at 14:27
  • Does this answer your question? [Get selected value/text from Select on change](https://stackoverflow.com/questions/5416767/get-selected-value-text-from-select-on-change) – pilchard Sep 01 '22 at 21:06

3 Answers3

1

First of all, you have to locate your select element in the script. To do this, you need to provide it with a specific id.

<select id="test_selector">
   <option>test1</option>
   <option>test2</option>
 </select>

Then you can use this id to access that selector in the JS. In order to get the updated value, chain it with the change event listener. Its callback receives the event parameter which contains the info you need.

 document.getElementById('test_selector').addEventListener('change', event => {
     console.log(event.target.value);
 });
Vitalii Romaniv
  • 731
  • 2
  • 8
  • 17
0

Another option is to do it on jquery if you feel more comfy with it

Give your select an id

<select id="id_selector">
   <option>test1</option>
   <option>test2</option>
 </select>

Use a jquery .change function to get the value of the selected option

$('#id_selector').change(function(){
    console.log($('#id_selector').val());
    //or console.log($(this).val()); to make the code shorter
});
Chris G
  • 1,598
  • 1
  • 6
  • 18
-2

Try this

 select.addEventListener('select',(e)=>{
 console.log(e.target.value);
 })
Patrick Iradukunda
  • 499
  • 1
  • 5
  • 15
  • wrong, and select is undefined – Chris G Aug 25 '22 at 14:29
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 29 '22 at 20:57