本文翻译自:jQuery get value of select onChange
I was under the impression that I could get the value of a select input by doing this $(this).val();
我的印象是我可以通过执行$(this).val();
来获取选择输入的值$(this).val();
and applying the onchange
parameter to the select field. 并将onchange
参数应用于选择字段。
It would appear it only works if I reference the ID. 它似乎只有在我引用ID时才有效。
How do I do it using this. 我该怎么做呢。
参考:https://stackoom.com/question/kuH0/jQuery获取select-onChange的值
Try this- 试试这个-
$('select').on('change', function() { alert( this.value ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="1">One</option> <option value="2">Two</option> </select>
You can also reference with onchange event- 你也可以参考onchange事件 -
function getval(sel) { alert(sel.value); }
<select onchange="getval(this);"> <option value="1">One</option> <option value="2">Two</option> </select>
I was under the impression that I could get the value of a select input by doing this $(this).val(); 我的印象是我可以通过执行$(this).val();来获取选择输入的值。
This works if you subscribe unobtrusively (which is the recommended approach): 如果您不引人注意地订阅(这是推荐的方法),这是有效的:
$('#id_of_field').change(function() {
// $(this).val() will work here
});
if you use onselect
and mix markup with script you need to pass a reference to the current element: 如果使用onselect
并将标记与脚本混合,则需要传递对当前元素的引用:
onselect="foo(this);"
and then: 然后:
function foo(element) {
// $(element).val() will give you what you are looking for
}
Look for jQuery site 寻找jQuery 网站
HTML: HTML:
<form>
<input class="target" type="text" value="Field 1">
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
JAVASCRIPT: JAVASCRIPT:
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
jQuery's example: jQuery的例子:
To add a validity test to all text input elements: 要为所有文本输入元素添加有效性测试:
$( "input[type='text']" ).change(function() {
// Check input( $( this ).val() ) for validity here
});
Try the event delegation method, this works in almost all cases. 尝试使用事件委派方法,几乎适用于所有情况。
$(document.body).on('change',"#selectID",function (e) {
//doStuff
var optVal= $("#selectID option:selected").val();
});
This is helped for me. 这对我有帮助。
For select: 对于选择:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox: 对于收音机/复选框:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});