我正在尝试使用jquery设置select2值。这可能是一个重复的问题,但我在这里已经阅读了30个不同的答案,但没有找到解决我问题的答案。
HTML code:
<div class="has_many_fields" data-required-has-many-fields-rows="1" id="location_account_associations"><input id="location_account_associations_attributes_0__destroy" name="location[account_associations_attributes][0][_destroy]" type="hidden" value="false" />
<div class="has_many_fields_row countable" id="location_account_associations_attributes_0">
<div class="form__row form__row--spreadsheet">
<div class="form__row__body">
<div class="form__row__field-wrapper">
<ul class="grid grid--no-gutters">
<li class="grid__6 grid__x--show">
Account Thing
<input id="location_account_associations_attributes_0_ab_account_id" name="location[account_associations_attributes][0][ab_account_id]" type="hidden" value="42" />
</li>
<li class="grid__5">
<select class="js-select2-combobox" id="location_account_associations_attributes_0_account_id" name="location[account_associations_attributes][0][account_id]" placeholder=" " reflection="#<ActiveRecord::Reflection::AssociationReflection:0x012fb5asd200e8>">
<option value=""></option>
<option value="1">Orange</option>
<option value="2">Apple</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
我尝试了多种不同的方法来选择“Orange”。请注意,当按下某个键击时,此jQuery会执行。此外,由于多种原因,HTML无法编辑。只能更改jQuery。
的Javascript / jQuery的:
(function() {
$(document).on("keydown", function(e) {
// ignore unless CTRL + ALT/COMMAND + N was pressed
if (!(e.keyCode == 78 && e.ctrlKey && e.altKey )) return
jQuery('[name*="[account_associations_attributes][0]').select2("val",1);
jQuery('[name*="[account_associations_attributes][0]').select2("val","Orange");
})
}())
答案 0 :(得分:6)
结束找到解决方案。
jQuery('[name*="[account_associations_attributes][0]"]').select2('val', '1')
答案 1 :(得分:2)
试试这个:
您可以通过选择ID来选择它
现场演示:http://jsfiddle.net/5Y9mG/10/
$(document).ready(function(){
$(document).on("keydown", function(e) {
// ignore unless CTRL + ALT/COMMAND + N was pressed
if (!(e.keyCode == 78 && e.ctrlKey && e.altKey )) return;
$('#location_account_associations_attributes_0_account_id option:eq(1)').prop('selected', true)
});
});
您也可以按ID和值选择它:
$('#location_account_associations_attributes_0_account_id option[value="1"]').prop('selected', true)
答案 2 :(得分:-1)
检测多个按键,特别是使用修饰符,非常棘手。
看一下this other post,然后确保你的keypress事件产生一个更基本的结果(很简单,比如alert()
),然后再添加更复杂的行为,例如更改下拉列表的值,根据浏览器和下拉列表本身也很棘手。