2014-01-10 118 views
4

我正在尝试使用jquery设置select2值。这可能是一个重复的问题,但我已阅读了30个不同的回复,并没有找到解决我的问题的答案。使用jquery设置select2输入的值

HTML代码:

<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="#&lt;ActiveRecord::Reflection::AssociationReflection:0x012fb5asd200e8&gt;"> 
          <option value=""></option> 
          <option value="1">Orange</option> 
          <option value="2">Apple</option> 
         </select> 
        </li> 
       </ul> 
      </div> 
     </div> 
    </div> 
</div> 

我已经尝试了多种不同的方法来获得 “橙色” 被选中。请注意,此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"); 
    }) 
}()) 

回答

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) 
+0

@Zack:你试过这个吗? –

+0

我没有尝试过,但我只是做了,它不会工作。我编辑的问题,包括更多的JavaScript ......也许这将有助于? – Zack

+0

@Zack:我已经更新了我的答案。看一看。 –

-1

检测多个按键,尤其是改性剂,是非常棘手的。

看看this other post然后确保你的按键事件产生一个更基本的结果(简单的东西,像一个alert())添加更复杂的行为像改变下拉列表的值之前,这也可能会非常棘手根据在浏览器和下拉本身。

+0

是的...我试过... ...事件工作正常。我还有其他50件事情。这是唯一不起作用的。 – Zack

7

结束查找解决方案。

jQuery('[name*="[account_associations_attributes][0]"]').select2('val', '1') 
+0

谢谢。这工作。有没有解决方案来做出多个选择/值?例如。值1,2和5. – ewroman

+0

我找到了。像这样:'select2('val',['1','2','5'])'从这里http://stackoverflow.com/questions/12889552/how-to-set-selected-value-in - 多值选择功能于jQuery的选择2 – ewroman