ruby-on-rails – jQuery autocomplete – 如何查看项目标签但提交项目值

我是 javascript的新手,我可能咬的比我可以咀嚼的多,但我试图让我的Rails网站上的 jQuery autcomplete小部件工作.

我有一个名为“链接”的页面,我希望能够将一个人分配给一个链接.使用自动填充我应该能够有一个文本框,其中包含自动填充建议的人名列表,选中后,人名仍保留在文本框中.但是当提交表单时,我不希望随表单发送的人名,我希望随表单发送的人员ID.

所以问题是如何选择人名,保留在文本框中,但一旦提交,则提交人员ID.

在Rails中,这是我从Person控制器提供JSON数据的方式:

def index  
  if params[:term]
    @people = Person.find(:all,:conditions => ['given_name LIKE ?',"#{params[:term]}%"],:limit => 5)
  else
    @people = Person.all
  end

  respond_to do |format|  
    format.html # index.html.erb  
    format.json { render :json => @people.to_json(:only => [:id,:given_name]) }
    end
end

以上输出以下JSON文本:

[{"person":{"id":1,"given_name":"Dale"}},{"person":{"id":2,"given_name":"sally"}},{"person":{"id":3,"given_name":"joe"}}]

使用jQuery自动完成插件,如何在建议的匹配中显示’given_name’,选择后在文本框中保留’given_name’,但在提交表单时发送’id’值.

我想我需要在javascript中指定要标记内容以及要发送的值.因为我只是掌握了javascript,如果你能解释你的答案是如何工作的,那将是值得赞赏的.谢谢.

解决方法

我能想出的最佳答案是为该人的id创建一个隐藏的输入字段.当您选择名称时,result()函数会使用id更新隐藏输入的值:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/demo/main.css" type="text/css" />
  <link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.bgiframe.min.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/lib/jquery.dimensions.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
  <script>
  $(document).ready(function(){
    // your data
    var data = [{"person":{"id":1,"given_name":"joe"}}];


    $("#person_name").autocomplete(data,{
      // formatting of choices in drop down
      formatItem: function(item) {
        return item.person.given_name;
      },// format of choice in input field
      formatResult: function(item) {
        return item.person.given_name + " (" + item.person.id + ")";
      }

      // when choice is made,update value of hidden field with the id
    }).result(function(event,data,formatted) {
      $("#person_id").val(data.person.id);
    });
  });
  </script>

</head>
<body>
  Select a person: <input id="person_name" /> (Dale,sally,joe)
  <input type="hidden" id="person_id"/>
</body>
</html>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...