当一个用户向另一个用户发送消息时。他们可以选择要发送到的个人资料类型。 (公共或管理员)...我正在检查后端,使用“ recipient_type”将其发送到哪个配置文件,如何获得自动完成功能以选择隐藏的单选按钮?
自动完成如下所示:
收件人:John Doe - Manager
要么
收件人:John Doe
模板:
<div class="hide">
<input type="radio" id="id_recipient_type" name="recipient_type" value="0" />
<input type="radio" id="id_recipient_type" name="recipient_type" value="1" />
</div>
<div class="inline-block">
<label for="id_omnibox"></label>
<input type="hidden" name="recipient_username" id="id_recipient_username" />
<input id="message-to" class="required input-text" style="width: 145%;"name="omnibox" placeholder="Search for user..." autocomplte="on" type="text" />
</div>
脚本:
$(document).ready(function(){
$.get('/autocomplete/message/', function(data) {
var completions = new Array();
var dict = JSON.parse(data, function(key, value) {
completions.push(key);
return value;
});
$('#message-to').autocomplete({
source: completions,
minLength: 1,
select: function(value, data){
$('#id_recipient_username').val(dict[data.item.value])
split_string = data.item.value.split("- ");
$('#id_recipient_type_'+(split_string[1]=="Manager"?"1":"0")).attr('checked', true);
}
});
});
});
最佳答案
为了使代码正常工作,您似乎需要更改或:
<div class="hide">
<input type="radio" id="id_recipient_type_0" name="recipient_type" value="0" />
<input type="radio" id="id_recipient_type_1" name="recipient_type" value="1" />
</div>
单选框ID。要么:
$('#id_recipient_type[value="'+(split_string[1]=="Manager"?"1":"0")+'"]').attr('checked', true);
jQuery选择器为
#id_recipient_type[value="1"]
或#id_recipient_type[value="0"]
。我会使用第一个解决方案,因为html中的id应该是唯一的。
您需要用拆分解决kmfk所述的问题,当找不到
' - '
字符串时,拆分会引发错误,因此请更改:split_string = data.item.value.split("- ");
至:
split_string = 'John Doe - Manage'.match(/ - (Manager)$/)
split_string = split_string != null ? "0" : "1";
关于javascript - 通过自动完成设置隐藏的单选按钮值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10250950/