php – How to access dropdonw value without refresh

Question:

Is there a way to get the value of the option chosen from my select, on the same page, without submitting 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.

Answer:

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 both selects too:

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

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

alert(soma);

})
Scroll to Top