【问题标题】:GenemuFormBundle Autocomplete resultsGenemuFormBundle 自动完成结果
【发布时间】:2015-08-02 22:48:41
【问题描述】:
我目前正在使用 GenemuFormBundle 来选择一个实体。假设我要选择实体“西瓜”。如果我只是在输入中输入“w”,它会显示一个列表,并且随着我输入的每个其他字母,列表会缩短,直到它只显示“西瓜”。
现在假设我输入“waterme”,并且列表中显示的唯一结果是“watermelon” 现在,我提交表单,它会寻找一个名为“waterme”的实体,找不到它,并返回“NULL”。
所以,我的问题是,当我的用户验证表单或关注另一个输入时,是否可以自动选择列表中显示的第一个结果?
【问题讨论】:
标签:
jquery
forms
symfony
autocomplete
【解决方案1】:
有点复杂,你必须在某处保留select2下拉列表的状态,当表单提交时,选择你想要的元素,如果在提交表单之前没有选择元素。这里是:
var currentChoice = null;
var $form = $("#your-form");
var $s2 = $("#your-select2-element");
$s2.on("select2-highlighting", function(event){
// this event is fired, when some choice is highlighted
// now store the current choice so we can retrieve it later
currentChoice = event.val;
});
$form.on('submit', function(){
//select something if it is not selected, and we have some highlighted choice
if (!$s2.select2('val') && currentChoice)
$s2.select2('val',currentChoice);
});