How to access dropdonw value without refresh

3

Is there a way to get the value of the selected option from my select, on the same page, without sending the form, when the user makes a change?

<select id="s_um" name="s_um">
                <option id="um_1" value="0"> 0 </option>
                <option id="um_2" value="1"> 1 </option>
                <option id="um_3" value="2"> 2 </option>
                <option id="um_4" value="3"> 3 </option>
                </select>

<select id="s_dois" name="s_dois">
                <option id="dois_1" value="0"> 0 </option>
                <option id="dois_2" value="1"> 1 </option>
                <option id="dois_3" value="2"> 2 </option>
                <option id="dois_4" value="3"> 3 </option>
                </select>

I would like to add the chosen values.

    
asked by anonymous 19.01.2016 / 13:20

2 answers

1

You can do this:

$('#s_dois').change(function() {

var soma = parseInt($('#s_um option:selected').val()) + parseInt($('#s_dois option:selected').val());

alert(soma);

})

See the fiddle: link

You can make the event for both selects as well:

$('#s_um, #s_dois').change(function() {

var soma = parseInt($('#s_um option:selected').val()) + parseInt($('#s_dois option:selected').val());

alert(soma);

})
    
19.01.2016 / 13:31
1

You can do this with jQuery:

$("select").change(function() {
  alert($(this).val()); // ou text()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><selectid="s_um" name="s_um">
  <option id="um_1" value="0">0</option>
  <option id="um_2" value="1">1</option>
  <option id="um_3" value="2">2</option>
  <option id="um_4" value="3">3</option>
</select>

<select id="s_dois" name="s_dois">
  <option id="dois_1" value="0">0</option>
  <option id="dois_2" value="1">1</option>
  <option id="dois_3" value="2">2</option>
  <option id="dois_4" value="3">3</option>
</select>

Or in javascript:

document.querySelector('select').addEventListener('change', function() {
  console.log(this.value);
});

See working at: jsfiddle

    
19.01.2016 / 13:27