How To Get The Value/Text Of Select Or Dropdown On Change Using JavaScript

We will learn how to get the value/text of select or dropdown on change in JavaScript using two different methods. Each method is rather straightforward, and you can choose whichever you want.

Get the Value/Text of Select or Dropdown on Change in JavaScript

By using function addEventListener()

Syntax:

addEventListener(type, listener)

Parameters:

• type: A case-sensitive string represents the event type of listening.
• listener: The function that receives a notification when the event of the given type occurs.

The addEventListener() method sets up a function that will be called whenever the specified event is delivered to the target. The following example will alert the selected option’s value and its text:

let body = document.getElementsByTagName("body")[0];
let s = document.createElement("select");
s.innerHTML =   
<option value="learn">-> Learn</option>
<option value="share"> -> Share</option>
<option value="it"> -> IT</option>;
body.appendChild(s);
});

Output:

learn-> Learn
share-> Share
it-> IT


The logic behind this method is very simple because we want to get the value/text of select or dropdown on change. The ‘type’ parameter must be “change” as it indicates the change event of an object. Hence, whenever it catches a change in the object, it will automatically execute the function in the second parameter.

By setting the “onchange” attribute.

Syntax:

object.onchange = function(){myScript};

Parameters:

• script: The script to run when event onchange is activated

The “onchange” attribute executes a script when a user changes the selected option of an element of type “select”:

let body = document.getElementsByTagName("body")[0];
let s = document.createElement("select");
s.innerHTML =   
<option value="learn">-> Learn</option>
<option value="share"> -> Share</option>
<option value="it"> -> IT</option>;
body.appendChild(s);

Output:

learn-> Learn
share-> Share
it-> IT

In addition, the ‘onchange’ occurs when the element loses focus after the content has been changed. Using the ‘onchange’ attribute is much easier than the first approach, especially when the function you want to execute is just some lines of code. However, when it comes to lots of statements, you might need to use the first approach instead, as it also provides you with the event listener callback.

Summary

We have learned how to get the value/text of select or dropdown on change in JavaScript using two different methods. It would help if you considered that each approach has its pros and cons. By referencing the ‘value’ property of the object, we can get its value or text of the selected option.

Maybe you are interested: