Home » Jquery » jquery – Bootstrap modal coded inside forms – rendered with model then OUTSIDE the form-Exceptionshub

jquery – Bootstrap modal coded inside forms – rendered with model then OUTSIDE the form-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a standard Rails app form with nested attributes. I have too many fields in the nested attributes so I figured I would create a modal window for these via Bootstrap. It looks roughly like this:

<body>
  <form>
    <div id="modal" class="modal">
      modal form input fields
    </div>
  </form>
</body> 

The issue I have is that when rendered in the browser I get this:

<body>
  <form>
  </form>
  <div id="modal" class="modal">
    modal form input fields
  </div>
</body>

The modal divs are all moved to the end of the body and hence the inputs not submitted with the form. The modals work just fine.

After searching I came across this (position:fixed):

https://getbootstrap.com/docs/4.0/components/modal/

I don’t know if it related but worth mentioning. Anyone else seen this? I can’t seem to find another related issue but could easily be using the wrong search terms etc.

UPDATE

Hunted through the BS code:

   // Move modal to body
    // Fix Bootstrap backdrop issue with animation.css

    // MOD Keeps the modals in place so you can hide them in a form

    $('.modal').appendTo("body");

Now – thoughts on how to prevent this? If it was one modal I could just move it back. The issue is I have multiple modals (one for each nested attribute which can be > 0). I can conceive making this work (ie. moving them all back) but ideally suppressing this would be better (easier).

How to&Answer:

Given my situation I choose to just move the divs back. It was not that bad:

<body>
  <form>
    <table>
      <tr>
        <td class="modal_id_1">
          <div id="modal_id_1" class="modal">
            modal form input fields
          </div>
        </td>
        <td class="modal_id_2">
          <div id="modal_id_2" class="modal">
            modal form input fields
          </div>
        </td>
      </tr>
    </table>
  </form>
</body>

After age load the modal divs are moved to the end of the body. I did this:

  $('.item_modal').each(function() {
    $(this).appendTo("td." + $(this).attr('id'));

Open to better answers – thanks to those that commented 👍