KeizerBridge
KeizerBridge

Reputation: 2757

How to get dynamically a value of a select tag?

I want to get dynamically the value of a select tag in my form. I do this actually

<select name="media_types_id" id="type">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

<script>
    var option = $("#type option:selected").val();
    console.log(option);
</script>

but this return the value of the option selected and it doesn't change when I change the option in my form. i select 1 and if I select 2 after it stays at value 1...

Upvotes: 3

Views: 4075

Answers (5)

howderek
howderek

Reputation: 2244

Use event handlers.

Event handlers call a function every time something happens.

Pure JS

var option = document.getElementById("type").value;
document.getElementById("type").onchange = function(e) {
    option = this.value;
}

Example: http://jsfiddle.net/howderek/FnT9T/3/

Upvotes: 1

freshbm
freshbm

Reputation: 5622

You need to bind change event to your select list:

<script>
  $(function() {
     $("#type").change(function() {
     console.log($(this).val());
    });
 });
</script>

Upvotes: 2

user2354869
user2354869

Reputation:

but your code runs globally. so for the first time , when page loads 1 is the selected value.

try your code inside change event

i.e.

$('#type').on("change",function(){
    var option = $("option:selected",this).val();
    console.log(option);
});

Upvotes: 3

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Try Following use change() event to get the selected value of a drop down list

$("#type").on("change",function(){
        var Option = this.val();
        console.log(Option);

});

Upvotes: 3

VisioN
VisioN

Reputation: 145388

Bind change event to your <select> element and use its value:

$("#type").on("change", function() {
    var option = this.value;
    console.log(option);
});

Also note that event binding should be done when the DOM is loaded, so either place this code right before </body> or use $(function() { }); handler.

Upvotes: 3

Related Questions