通过自动完成设置隐藏的单选按钮值

时间:2012-04-20 17:42:06

标签: javascript jquery html

当用户向其他用户发送消息时他们可以选择要发送的配置文件类型。 (Common或Manager)...我正在检查后端使用“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);
            }     
        });
    });
});

2 个答案:

答案 0 :(得分:2)

为了使您的代码能够正常工作,您需要更改或:

<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);

#id_recipient_type[value="1"]#id_recipient_type[value="0"]的jquery选择器。

我会使用第一个解决方案,因为在html ID中应该是唯一的。

您需要解决kmfk所述的问题,并在找不到' - '字符串时抛出错误,因此请更改:

split_string = data.item.value.split("- ");

要:

split_string = 'John Doe - Manage'.match(/ - (Manager)$/)
split_string = split_string != null ? "0" : "1";

答案 1 :(得分:1)

查看代码示例,这些行似乎是个问题:

split_string = data.item.value.split("- ");
$('#id_recipient_type_'+(split_string[1]=="Manager"?"1":"0")).attr('checked', true);

- Manager不在字符串中时,该分割将成为问题 - 并且您要查找的ID不存在。

也许这样做:

var valAttr = data.item.value.indexOf("- Manager") > 0 ? 1 : 0;
$('#id_recipient_type [value="'+valAttr+'"]').attr('checked', true);