微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

原文地址:https://www.jb51.cc/ruby/268586.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐