2012-04-20 54 views
0

当用户向另一个用户发送消息时。他们可以选择要发送到哪种类型的配置文件。 (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

看来,为了你的代码工作,你需要更改或:

<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 ids中应该是唯一的。

你需要解决的kmfk与分裂它抛出一个错误时没有找到' - '串指出一个问题,所以改变:

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

要:

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

+1。不得不编辑我的答案,注意到ID不存在,但没有提及它。当“ - ”在字符串中不存在时,仍会遇到'split_string [1]'上的未定义错误。 – kmfk 2012-04-20 17:59:35

+0

同意,我会改变我的答案与正则表达式一起工作。谢谢你的提示。 – 2012-04-20 18:00:58

+0

你们真棒。感谢您的帮助! – Modelesq 2012-04-20 18:24:55

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