Display selected option in select with JS

Asked

Viewed 833 times

2

I have an excerpt of code where I wish to pick up the value of option selected, with Javascript, and give a alert with that value. However, every time he gives the value as undefined. I made a line to put in a input also, just to test, and it didn’t work.

Here is the code:

$("select[name='estado']").change(function() {
    var estado = document.getElementsByTagName("estado").value;
    document.getElementById("teste").setAttribute("value", estado);
    alert('estado ' + estado);
});
<select id="txt-model" class="field-50" name="estado">
    <option value="">Selecione um Estado</option>
    <option value="AC">Acre</option>
    <option value="AL">Alagoas</option>
    <option value="AP">Amapá</option>
    //... O resto dos estados
</select>

<input type="text" id="teste" name="teste">

  • use $(this). val() to get the value in the selector.

1 answer

5

The target the selector is not correct, one way is to get the direct value by the element event:

$("select[name='estado']").change(function() {
    var estado = this.value;
    alert('estado ' + estado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="txt-model" class="field-50" name="estado">
    <option value="">Selecione um Estado</option>
    <option value="AC">Acre</option>
    <option value="AL">Alagoas</option>
    <option value="AP">Amapá</option>
    //... O resto dos estados
</select>

<input type="text" id="teste" name="teste">

A little about selectors.

Browser other questions tagged

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