jQuery的后自动完成故障动态添加额外的文本输入字段 [英] jQuery autocomplete failing after dynamically adding additional text input field

查看:170
本文介绍了jQuery的后自动完成故障动态添加额外的文本输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

**更新**我改变了HTML的id上课。并纳入目前的顶级答案的建议。自动完成现在的作品,但自动完成选项列表没有成功显示动态阿迪文本输入字段。它适用于原虽然。

我添加下面的更新code。

我只是说jQuery用户界面自动完成一个形式,我的Rails应用程序。该功能的工作不过罚款,当我与动态相同的类添加其他输入字段不起作用?

 < A HREF =#类=addNewIngredient>添加成分< / A>

在动态添加一个附加的字段,原始字段的自动完成功能继续没有任何问题的工作,但新加入的字段的自动完成功能不起作用。

为什么会自动完成功能失效的动态添加字段,如果输入字段都有着相同的ID?

的application.js

  $(文件)。就绪(函数(){
$(。addNewIngredient)。在('点击',功能(E){
  亦即preventDefault();
$(ingredientField)附加($(#new_ingredients_form)的HTML()。)。
$(。select_ingredient)。自动完成({
        的minLength:2,
        来源:'/成份',
        重点:函数(事件,UI){
            $('。select_ingredient)VAL(ui.item.name)。
            返回false;
        },
        选择:函数(事件,UI){
            $('。select_ingredient)VAL(ui.item.name)。
    $('。link_ingredient_id)VAL(ui.item.id)。
            返回false;
        }
    })
    。数据(UI-自动完成)._ renderItem =功能(UL,项目){
        返回$(<立GT;< /李>中)
            。数据(UI-自动完成项目,项目)
            .append(&所述a取代;+ item.name +&下; / A>中)
            .appendTo(微升);
    };
});$(。removeIngredient)。在('点击',功能(E){
  亦即preventDefault();
$(ingredientField #new_ingredients_form。)空();
});
});

new.html.erb

 < H1>创建膳食和LT; / H1>
<%=的form_for(@meal)做| F | %GT;  <%= f.label:名称%>
  <%= f.text_field:名称%>< BR />  < D​​IV CLASS =ingredientField>
    <%=渲染ingredient_form%GT;
  < / DIV>
  < A HREF =#类=addNewIngredient>添加成分< / A>
  &所述; A HREF =#类=removeIngredient>删除成分&下; / A>  &所述;%= f.label:CLEAN_UP%GT;
  <%= f.select:CLEAN_UP,options_for_select([,],[低,低],[医学,配有],[高,高] ])%GT;< BR />  <%= f.label:自制%GT;
  <%= f.select:自制,options_for_select([是,真],[否,假])%GT;< BR />  <%= f.submit保存%GT;
<%结束%GT;

_ingredient_form.html.erb

 <脚本类型=文/ JavaScript的>
    $(函数(){
 //下面是这将是自动完成的文本字段的名称
    $('。select_ingredient')。自动完成({
 //这表明必须键入自动完成查找在比赛前charcters的最小长度。
            的minLength:2,
 //这是的auocomplete建议的来源。在这种情况下,从人的控制器,JSON格式名称的列表。
            来源:'<%= ingredients_path(:JSON)%GT;,
  //当您移动向上向下的建议名单,与键盘这将更新文本字段。在我们的情况下,它将反映您在这是person.given_name建议看到相同的值。
            重点:函数(事件,UI){
                $('。select_ingredient)VAL(ui.item.name)。
                返回false;
            },
 //一旦在下拉列表中选择一个值,请执行以下操作:
            选择:函数(事件,UI){
 //将person.given_name值放入称为select_origin文本字段...
                $('。select_ingredient)VAL(ui.item.name)。
 //并将person.id到名为link_origin_id隐藏的文本框。
        $('。link_ingredient_id)VAL(ui.item.id)。
                返回false;
            }
        })
 //下面的code是直接从jQuery的例子。它是什么格式的数据将显示在下拉列表框,可定制。
        。数据(UI-自动完成)._ renderItem =功能(UL,项目){
            返回$(<立GT;< /李>中)
                。数据(item.autocomplete项)
 //现在刚刚要显示在列表中person.name。
                .append(&所述a取代;+ item.name +&下; / A>中)
                .appendTo(微升);
        };
    });
    < / SCRIPT>
< D​​IV CLASS =ingredientsFormID =new_ingredients_form>
  <%= label_tag成分%GT;
  <输入类=select_ingredient/>
  <输入类=link_ingredient_idNAME =链接[ingredient_id]类型=隐藏/>
  <%= label_tag份%GT;
  <%= text_field_tag​​份[]%GT;
< / DIV>

ingredients_controller.rb

 类IngredientsController< ApplicationController中
  的before_filter:的authenticate_user!  高清指数
    如果PARAMS [:长期]
      @ingredients = Ingredient.find(:全部:条件=>的名字怎么样?,#{PARAMS [:长期]}%​​])
    其他
      @ingredients = Ingredient.all
    结束    做的respond_to |格式|
      format.html
      format.json {渲染:JSON => @ ingredients.to_json}
    结束
  结束
结束


解决方案

通过使用固定它的$(document)。在(keydown.autocomplete,。select_ingredient功能(E){ }

全面修订功能:

 <脚本类型=文/ JavaScript的>
$(函数(){
$(文件)。在(keydown.autocomplete,。select_ingredient功能(E){
$(本).autocomplete({
         的minLength:2,
        来源:'<%= ingredients_path(:JSON)%GT;,
        重点:函数(事件,UI){
            $(本).VAL(ui.item.name);
            返回false;
        },
         选择:函数(事件,UI){
             $(本).VAL(ui.item.name);
     $('。link_ingredient_id)VAL(ui.item.id)。
            返回false;
        }
    })
     。数据(UI-自动完成)._ renderItem =功能(UL,项目){
        返回$(<立GT;< /李>中)
            。数据(item.autocomplete项)
             .append(&所述a取代;+ item.name +&下; / A>中)
            .appendTo(微升);
    };
  });
});
< / SCRIPT>

** UPDATE ** I changed the HTML id's to classes. And incorporated the advice in the current top answer. The autocomplete now works but the autocomplete option list DOES NOT successfully display for the dynamically adde text input field. It works for the original though.

I have added the updated code below.

I just added jQuery UI autocomplete to a form in my Rails app. The feature works fine however it doesn't work when I dynamically add another input field with the same class?

<a href="#" class="addNewIngredient">Add ingredient</a>

After dynamically adding an additional field, the original field's autocomplete feature continues to work without any issues but the newly added field's autocomplete feature does not work.

Why would the autocomplete feature fail for the dynamically added field if the input fields all share the same id?

application.js

$(document).ready(function(){
$(".addNewIngredient").on('click', function(e){
  e.preventDefault();
$(".ingredientField").append($("#new_ingredients_form").html());
$(".select_ingredient").autocomplete({
        minLength: 2,
        source: '/ingredients',
        focus: function(event, ui) {
            $('.select_ingredient').val(ui.item.name);
            return false;
        },
        select: function(event, ui) {
            $('.select_ingredient').val(ui.item.name);
    $('.link_ingredient_id').val(ui.item.id);
            return false;
        }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "ui-autocomplete-item", item )
            .append( "<a>" + item.name + "</a>" )
            .appendTo( ul );
    };
});

$(".removeIngredient").on('click', function(e){
  e.preventDefault();
$(".ingredientField #new_ingredients_form").empty();
});
});

new.html.erb

<h1>Create Meal</h1>
<%= form_for(@meal) do |f| %>

  <%= f.label :name %>
  <%= f.text_field :name %><br/>

  <div class="ingredientField">
    <%= render "ingredient_form" %>
  </div>
  <a href="#" class="addNewIngredient">Add ingredient</a>
  <a href="#" class="removeIngredient">Remove ingredient</a>

  <%= f.label :clean_up %>
  <%= f.select :clean_up, options_for_select([["", ""],["Low", "low"], ["Med", "med"], ["High", "high"]]) %><br/>

  <%= f.label :homemade %>
  <%= f.select :homemade, options_for_select([["Yes", true],["No", false]])  %><br/>

  <%= f.submit "Save" %>
<% end %>

_ingredient_form.html.erb

    <script type="text/javascript">
    $(function() {
 // Below is the name of the textfield that will be autocomplete
    $('.select_ingredient').autocomplete({
 // This shows the min length of charcters that must be typed before the autocomplete looks for a match.
            minLength: 2,
 // This is the source of the auocomplete suggestions. In this case a list of names from the people controller, in JSON format.
            source: '<%= ingredients_path(:json) %>',
  // This updates the textfield when you move the updown the suggestions list, with your keyboard. In our case it will reflect the same value that you see in the suggestions which is the person.given_name.
            focus: function(event, ui) {
                $('.select_ingredient').val(ui.item.name);
                return false;
            },
 // Once a value in the drop down list is selected, do the following:
            select: function(event, ui) {
 // place the person.given_name value into the textfield called 'select_origin'...
                $('.select_ingredient').val(ui.item.name);
 // and place the person.id into the hidden textfield called 'link_origin_id'.
        $('.link_ingredient_id').val(ui.item.id);
                return false;
            }
        })
 // The below code is straight from the jQuery example. It formats what data is displayed in the dropdown box, and can be customized.
        .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
 // For now which just want to show the person.name in the list.
                .append( "<a>" + item.name + "</a>" )
                .appendTo( ul );
        };
    });
    </script>


<div class="ingredientsForm" id="new_ingredients_form">
  <%= label_tag "ingredients" %>
  <input class="select_ingredient"/>
  <input class="link_ingredient_id" name="link[ingredient_id]" type="hidden"/>
  <%= label_tag "servings" %>
  <%= text_field_tag "servings[]" %>
</div>

ingredients_controller.rb

class IngredientsController < ApplicationController
  before_filter :authenticate_user!

  def index
    if params[:term]
      @ingredients = Ingredient.find(:all,:conditions => ['name LIKE ?', "#{params[:term]}%"])
    else
      @ingredients = Ingredient.all
    end

    respond_to do |format|
      format.html
      format.json { render :json => @ingredients.to_json }
    end
  end
end

解决方案

Fixed it by using $(document).on("keydown.autocomplete",".select_ingredient",function(e){}

Fully revised function:

<script type="text/javascript">
$(function() {
$(document).on("keydown.autocomplete",".select_ingredient",function(e){
$(this).autocomplete({
         minLength: 2,
        source: '<%= ingredients_path(:json) %>',
        focus: function(event, ui) {
            $(this).val(ui.item.name);
            return false;
        },
         select: function(event, ui) {
             $(this).val(ui.item.name);
     $('.link_ingredient_id').val(ui.item.id);
            return false;
        }
    })
     .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
             .append( "<a>" + item.name + "</a>" )
            .appendTo( ul );
    };
  });
});
</script>

这篇关于jQuery的后自动完成故障动态添加额外的文本输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆