How to access dropdonw value without refresh

Asked

Viewed 127 times

3

There is a way to take the value of the chosen option of my select, on the same page, without submitting the form, at the time 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.

  • Have you thought about using jquery?

2 answers

1

You can do that 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>
<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>

Or in javascript:

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

See working in: jsfiddle

1

You can do it like this:

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

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

alert(soma);

})

See the fiddle: https://jsfiddle.net/hq8mv7xw/

You can make the event for the two 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);

})

Browser other questions tagged

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