admin管理员组文章数量:1279049
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...
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...
Share Improve this question asked May 6, 2013 at 13:49 KeizerBridgeKeizerBridge 2,7577 gold badges26 silver badges40 bronze badges 1- See this other question stackoverflow./questions/11179406/… – Alberto Zaccagni Commented May 6, 2013 at 13:51
5 Answers
Reset to default 3Bind 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.
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);
});
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);
});
You need to bind change event to your select list:
<script>
$(function() {
$("#type").change(function() {
console.log($(this).val());
});
});
</script>
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/howderek/FnT9T/3/
本文标签: javascriptHow to get dynamically a value of a select tagStack Overflow
版权声明:本文标题:javascript - How to get dynamically a value of a select tag? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741220204a2360825.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论