在Rails表单中的jQuery自动完成

时间:2012-03-23 03:19:17

标签: jquery ruby-on-rails forms autocomplete

我有一个电子邮件的Rails表单,我想在Receiver字段中自动完成。这是我做的:

= f.label :recipient_id, "Send to:"
= text_field_tag :recipient_id, nil
:javascript
 $(function() {
    $( "#recipient_id" ).autocomplete({
        source: "#{escape_javascript url_for(:action => 'recipient_autocomplete',
                     :controller => 'sent')}",
        minLength: 2,
        select: function( event, ui ) {
            $('input#recipient_id').attr('value', ui.item.value);
            ui.item.value = ui.item.label
        }
    });
});

在我的控制器中,我有:

  def recipient_autocomplete
    @users= User.all(:conditions => ['first_name LIKE ? OR last_name LIKE?', 
      "%#{params[:term]}%", "%#{params[:term]}%"])
    render :json => @users.collect {|x| {:label=>x.full_name, :value=>x.id}}.compact
  end

json调用工作正常并显示全名OK。这是元素:

<input type="text" name="recipient_id" id="recipient_id" class="ui-autocomplete-input"
  autocomplete="off" role="textbox" aria-autocomplete="list" 
  aria-haspopup="true" value="158">

但是,当我点击发送(相当于提交)时,会发送收据全名而不是receiptient_id。

如何告诉Rails表单获取输入字段的值而不是其标签?

2 个答案:

答案 0 :(得分:1)

你有一个关于这个

的非常好的轨道演员here

答案 1 :(得分:1)

错误的HTML规范说text_field的文本是它要返回的值。但您可以使用hidden_field来传递_id,就像这样,

= f.label :recipient_id, "Send to:"
= text_field_tag :recipient_name, nil
= hidden_field_tag :recipient_id, nil
:javascript
 $(function() {
    $( "#recipient_id" ).autocomplete({
        source: "#{escape_javascript url_for(:action => 'recipient_autocomplete',
                     :controller => 'sent')}",
        minLength: 2,
        select: function( event, ui ) {
            $('input#recipient_name').val(ui.item.label);
            $('input#recipient_id').val(ui.item.value);
        }
    });
});

那来自This JqueryUI page