[英]Set value of two elements with same css class
I am using same css for a select dropdown and a input textbox. 我对选择下拉列表和输入文本框使用相同的CSS。 I set the values in jquery like this: 我像这样在jquery中设置值:
$('.a').val('2');
When checking the value of the select and input elements, they are correctly assigned but when I display their values via console.log, I get undefined for both. 在检查select和input元素的值时,它们已正确分配,但是当我通过console.log显示它们的值时,两者都未定义。 Why is that? 这是为什么?
console.log($('.a').find('select').val());
console.log($('.a').find('input').val());
Result: 结果:
undefined
undefined
Here's my fiddle: http://jsfiddle.net/04oLs3he/12/ 这是我的小提琴: http : //jsfiddle.net/04oLs3he/12/
Your selector is incorrect (no need of find
). 您的选择器不正确(无需find
)。 Try following 尝试跟随
$('.a').val('2'); console.log($('select.a').val()); console.log($('input.a').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="a"> <option value="1">One</option> <option value="2">Two</option> </select> <input type="text" class="a" value="Three">
Don't use .find()
to get the value, because it will search for children input
/ select
elements inside your selected element. 不要使用.find()
来获取值,因为它会在所选元素内搜索子级input
/ select
元素。
And don't use the same selector
to get both elements, use $('input.a')
to get the input
and $('select.a')
to get the dropdown element: 并且不要使用相同的selector
来获取两个元素, $('input.a')
使用$('input.a')
获得input
并使用$('select.a')
获得dropdown元素:
console.log($('select.a').val());
console.log($('input.a').val());
Note: 注意:
If you want to change the input
value when you change the option in the select
, use the change()
event to track this change. 如果要在更改select
的选项时更改input
值,请使用change()
事件跟踪此更改。
Demo: 演示:
$('select.a').change(function() { $('input.a').val($(this).val()); }); console.log($('select.a').val()); console.log($('input.a').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="a"> <option value="1">One</option> <option value="2">Two</option> </select> <input type="text" class="a" value="Three">
Try using filter
instead. 尝试改用filter
。 find
will try to find child elements of the selected one unlike filter which will filter the selected elements: find
会尝试查找所选元素的子元素 ,而不是过滤器,后者会过滤所选元素:
$('.a').val('2'); console.log($('.a').filter('select').val()); console.log($('.a').filter('input').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="a"> <option value="1">One</option> <option value="2">Two</option> </select> <input type="text" class="a" value="Three">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.