6

So i have a page and upon click button, it opens up a nested field and i want to hide one of the div in the filed upon click but so far my function doesnt work.

my js file

$('body').on('click', '#main-applicant-btn', function() {

    event.stopPropagation();
    var prependData = $('.main-applicant').children().first().clone();
    prependData.find("div.checkbox").replaceWith( $( "div.checkbox.hide" ));
    var prependedData = $('.main-applicant').children().last();
    var list = document.getElementsByClassName("main-applicant");
    list.insertBefore(prependData, prependedData);
  })

my applicant.html.erb file

<div class="form-group">
        <%= f.link_to_add "", :applicant_commitments, :class => "glyphicon glyphicon-plus-sign pointer add", :id => "main-applicant-btn", :data => {:target => "#main-applicant-#{rand}"} %>
      </label>
    </div>
    <span id="main-applicant-<%= rand %>" class="main-applicant">
          <%= f.simple_fields_for :applicant_commitments do |applicant_commitment| %>
            <%= render "existing_commitment_fields", {:f => applicant_commitment, :instalment => true, :type => 'existing_commitment_applicant'} %>
          <% end %>
        </span>

my nested field existing_commitment_fields.html.erb

 <div class="form-group monthly-instalment-lender-checkbox">
      <div class="col-sm-3" id="checkbox-existing-fields">
          <div class="checkbox">
            <label>
              <span>Joint Name</span>
              <%= f.input_field :joint_name, as: :boolean, class: "joint-name-commitment" %>
            </label>
          </div>
        </div> 
    </div>

So upon click i want to the main-applicant-btn and when it displays the nested_fields, i will hide the div.checkbox but so far when i try this code, i get error .insertBefore() is not a function.

Anyone has any clues on how to append or force javascript to run code after it has loaded?

1 Answer 1

8

insertBefore is a Node method.
document.getElementsByClassName() method returns an HTMLCollection.

You've got to iterate through this HTMLCollection or to pick one of the elements inside it to actually touch the nodes and use their method :

list[0].insertBefore(...,...)

Also, as mentioned by @nnnnnn, "the insertBefore() method isn't expecting jQuery objects as arguments.".
So either you use plain javascript methods like document.querySelector('') or you call the target of the jQuery object ($(...)[0])

Sign up to request clarification or add additional context in comments.

1 Comment

Also the insertBefore() method isn't expecting jQuery objects as arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.