Reputation: 11
I have a select
field with some options.
The thing is that when I try to get the value
of the selected option, I get the default value of the list.
Here's my code:
<div id='aux_motivo'>
<select name='id_aux_motivo' id='id_aux_motivo' class="combo4" >
<option value="">Select</option>
<option value="1" >Opt 1</option>
<option value="2" >Opt 2</option>
<option value="3" >Opt 3</option>
<option value="4" >Opt 4</option>
<option value="5" >Opt 5</option>
</select>(*)
</div>
This is the code I use for getting the value
:
var id_aux_motivo=$('#id_aux_motivo').val();
For some reason, instead of getting the value from the option I choose, I keep getting "", as if I chose "Select".
PS:Sorry for the bad english.
Upvotes: 0
Views: 1176
Reputation: 1
First check your HTML ID id_aux_motivo
, it should be unique.
If it is, then the below listed solutions will work:
var id_aux_motivo= $("#id_aux_motivo").find(":selected").val() ;
alert(id_aux_motivo);
or
alert($("#id_aux_motivo").val());
Upvotes: 0
Reputation: 11
Finally, I used var id_aux_motivo= $(this).find(":selected").val() ;
to assign the value to the variable.
Other options didn't work out.
Upvotes: 1
Reputation: 1709
Bind an event handler to the "change" event, or trigger that event on the element:
<script type="text/javascript">
$(document).ready(function () {
$('#id_aux_motivo').on("change", function () {
var id_aux_motivo = $('#id_aux_motivo').val();
console.log(id_aux_motivo);
});
});
</script>;
Try this jsfiddle example.
Upvotes: 0