Run JS function when user choose Select

Asked

Viewed 382 times

1

I have a select in html, and I want it to run a function when the user chooses any option. I appreciate the help.

                <select id="frmOperadora0" name="frmOperadora">
                    <option value="0">-----</option>
                    <option value="VV">Vivo</option>
                    <option value="CL">Claro</option>
                    <option value="TM">Tim</option>
                    <option value="OI">Oi</option>
                    <option value="NX">Nextel</option>
                    <option value="AL">Algar</option>
                    <option value="SE">Sercomtel</option>
                    <option value="MV">MVNO's </option>
                </select>
  • https://developer.mozilla.org/en-US/docs/Web/API/Element/addEventListener you can add a "change" event to that element.

2 answers

2


Use the parameter (HTML event) onChange to call the function.

HTML code:

<select id="frmOperadora0" name="frmOperadora" onChange="teste()">
                    <option value="0">-----</option>
                    <option value="VV">Vivo</option>
                    <option value="CL">Claro</option>
                    <option value="TM">Tim</option>
                    <option value="OI">Oi</option>
                    <option value="NX">Nextel</option>
                    <option value="AL">Algar</option>
                    <option value="SE">Sercomtel</option>
                    <option value="MV">MVNO's </option>
</select>

Script in Javascript:

teste = function() {
  alert('testando');
}

There are other events you can use, take a look at the site below:

https://www.w3schools.com/tags/ref_eventattributes.asp

0

Tries

function myFunction(){
alert(document.getElementById('frmOperadora0').value);
}
<select id="frmOperadora0" name="frmOperadora" onChange="myFunction()">
                <option value="0">-----</option>
                <option value="VV">Vivo</option>
                <option value="CL">Claro</option>
                <option value="TM">Tim</option>
                <option value="OI">Oi</option>
                <option value="NX">Nextel</option>
                <option value="AL">Algar</option>
                <option value="SE">Sercomtel</option>
                <option value="MV">MVNO's </option>
            </select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.