Show selected option in select with JS

2

I have a code snippet where I want to get the value of option selected with JavaScript, and give alert with that value. However, every time it gives the value as undefined . I made a line to put in a input too, just to test, and it did not 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">
    
asked by anonymous 23.05.2017 / 15:13

1 answer

5

The target in the selector is not correct, one way is to get the direct value for the element's 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><selectid="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 .

    
23.05.2017 / 15:16