简体   繁体   中英

Why is my object.children undefined?

I'm running javascript on Ruby on Rails to insert a form dynamically into a page when the user clicks on a link.

It's not working, but one particular bug gets my goat: that my form return form.children UNDEFINED in the debugging console.

Here is the form (in Rails):

<div class="field">
<%= f.label :name, 'Tag:' %>
<%= f.text_field :name %>   
</div>

And here is the javascript in application.js;

function add_fields(link, association, form) {
console.log(form);
console.log(form.children);
link.insertBefore(form, link.previousSibling.previousSibling);
}

I have tested whether the app actually calls the javascript by outputting text and the like and it works. The problem is clearly with my form.

Finally, the console output:

<div class="field">
<label for="post_tags_attributes_4_name">Tag:</label>
<input id="post_tags_attributes_4_name" name="post[tags_attributes][4][name]" size="30" type="text" />  
</div> application.js:21
undefined application.js:22
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 

By the way, I'm trying to implement railscast #197 on dynamically inserted nested forms and it's been a disaster!

--EDIT---

Here is how I call the add_fields function that builds the field element:

The ruby function:

module TagsHelper
    def link_to_add_fields(name, post_form, association)
        new_object = post_form.object.class.reflect_on_association(association).klass.new
        tag_field = post_form.fields_for :tags, new_object do|tag_form|
            render("tag_field", :f=>tag_form)
        end
        #debugger
        link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(tag_field)}\")")
    end
end

And here is the tag_field html:

<div class="field">
    <%= f.label :name, 'Tag:' %>
    <%= f.text_field :name %>   
</div>

Clearly this won't work because an element can't have a child that is also a sibling.

link.insertBefore(form, link.previousSibling.previousSibling);

Your code want's to put form as a child of link and before one of link 's siblings, which would be impossible.

Remember, .insertBefore must be called from the parent that it's being inserted into. So to insert form before link , the .insertBefore must be called from the parent of link .


So maybe you meant to use link.parentNode instead.

link.parentNode.insertBefore(form, link.previousSibling.previousSibling);

This will insert form before the second previous sibling of link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM