【问题标题】:jQuery autocomplete failing after dynamically adding additional text input field动态添加其他文本输入字段后,jQuery自动完成失败
【发布时间】:2014-09-03 08:34:16
【问题描述】:

** 更新 ** 我将 HTML id 更改为类。并将建议合并到当前的最佳答案中。自动完成现在可以工作,但自动完成选项列表没有成功显示动态添加文本输入字段。但它适用于原版。

我在下面添加了更新的代码。

我刚刚在我的 Rails 应用程序的表单中添加了 jQuery UI 自动完成功能。该功能工作正常,但是当我动态添加具有相同类的另一个输入字段时它不起作用?

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

动态添加额外字段后,原字段的自动填充功能继续正常工作,但新添加的字段的自动填充功能不起作用。

如果输入字段都共享相同的 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

【问题讨论】:

    标签: javascript jquery ruby-on-rails-3 jquery-ui autocomplete


    【解决方案1】:

    使用$(document).on("keydown.autocomplete",".select_ingredient",function(e){}修复它

    完全修改功能:

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

    【讨论】:

    • 你终于做到了.. :D
    【解决方案2】:

    试试这个:

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

    看第一个答案here.

    您可以做的其他事情是:在函数中编写您的 jquery 代码(比如 applyJquery() )并编写 href="#" onclick="applyJquery();href="javascript:applyJquery();

    Jquery 通常不能像处理静态元素那样处理动态创建的元素。

    使用.on() 参见示例here

    编辑:写:$(document).on("event",".class",function(e){ $(this).autocomplete({ //write something });

    【讨论】:

    • bdw 你为什么用href="javascript:;" 为什么不用href='#'
    • 那行不通。它与 href="javascript:;" 有关系吗在链接中? 添加成分
    • 哈!我晚了几秒钟。让我现在试试。
    • 刚刚切换到 href='#' 还是不行:(
    • 好的,我试试。忘了说有个小错误,就是函数没有传入“e”,不过我加了,还是不行。
    【解决方案3】:

    应该是

    $('form').on('click', '#addNewIngredient', function() {...
    

    但是重复的 ID 是无效的 html,所以你应该使用类名而不是 id 属性,例如

    <a href="javascript:;" class="addNewIngredient">Add ingredient</a>
    

    $('form').on('click', '.addNewIngredient', function() {...
    

    【讨论】:

    • 我将所有 id 更改为类,尝试了建议的代码,但仍然无法正常工作。对我还可以尝试什么有什么想法?
    • 我做了一些更改,但仍然无法正常工作。我更新了问题。
    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2021-06-15
    • 2014-09-30
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多