In this blog I will be going over how to use JavaScript to interact with select elements. First I think it is important to go over what a select element is and how it can be used. A select element allows a user to select an item out of the choices that they are given. It is very similar to a comboBox in Visual Studio. However in this case the options must be provided through code.

-NFL example:

<select id="nflChoice"> 
    <option>Packers</option>
    <option>Vikings</option>
    <option>Bears</option>
    <option>Lions</option>   
</select> 

While HTML can provide the select box it needs help for it to have any functianality. That is where JavaScript comes in. In this next example a button will be added to allow the user to select their favorite team from the options given.

NFL JavaScript example:

const btn = document.querySelector('#btn');
    const sb = document.querySelector('#nflChoice')
    btn.onclick = (event) => {
        alert("Your favorite NFC North team is the "+sb.value+"!");
    };

This previous example shows what is needed for a button to show the item selected from the select combobox. A DOM API has to be used to assign the id of both the button and the select element to constants which can then be used in an event. Both getElementById and querySelector can work for the last example. This could be used anywhere a combo box is needed. Whether that be selecting your favorite team, selecting the state you were born in, or selecting a color.

A few other notes is that the select tag has a multiple option which allows a user to select multiple choices. JavaScript doesn't have to return the value of the constant it can also return the selectedIndex. A value can be assigned to the options that can be returned. In my example I wanted the team name returned so the value option was excluded.