Target the current value of an option list using js, and add that value to an object?

Viewed 263

HTML

<div class="options-container">
 <select id="all-options">
  <option value="0" selected>NY</option>
  <option value="1">LA</option>
  <option value="2">Toronto</option>
  <option value="3">Paris</option>
 </select>
</div>

JS

let selectedOption = {};
let allOptions = document.getElementById('all-options');
let optionValue = allOptions.options[all-options.selectedIndex].value;
if (optionValue == "0") {
    selectedOption.value === "0"
} else if (optionValue  === "1") {
    selectedOption.value === "1"
} else if (optionValue  === "2") {
    selectedOption.value === "2"
} else if (optionValue  === "3") {
    selectedOption.value === "3"
};

I'm attempting to target the current value of an option list element in my HTML file using JS so that I can add that value to the selectedOption object. The value can be added either as a string or number object.

1 Answers

Defining the Event Listener

You're going to want to define an event listener in your <select>. For example:

        function onSelectItem(evt)
        {
            let value = evt.target.selectedOptions[0].value;
            let text = evt.target.selectedOptions[0].text;

            // Assign it how you want here:
            selectedOption = value;
        }

You can't really "push" to an object. If you meant an array, change the selected option to an array ([]) and do selectedOption.push(value). If you want a useful object, however, you could just assign it to evt.target.selectedOptions[0].

Attaching the Listener

After that, you can attach it in html, and pass the event object via the default event variable:

    <select id="all-options" onchange="onSelectItem(event)">
      <option value="0">NY</option>
      <option value="1">LA</option>
      <option value="2">Toronto</option>
      <option value="3">Paris</option>
    </select>

or more Javascript when the page loads (by setting the onload attribute to "init()" in <body>):

        function init()
        {
            let menu = document.getElementById('all-options');

            menu.addEventListener('change', onSelectItem);
            // Since it seems that you also want a default selected value when the 
            // page loads, you should probably also initialize your `selectedOption` to `0`.
            selectedOption = menu.selectedOptions[0].value;
        }
Related