Mike
Mike

Reputation: 199

Move form element outside the form, and place it inside another div

I have a sidebar on my page with search/filter form. What I trying to do is to move one of the elements (sort order dropdown) from this form, outside the form with CSS/JS and display it inside div on the right side. Is it possible without loosing form functionallity? Please chcek my code:

<div class="left-sidebar">
  <form>
    <div class="move-this-outside">Dropdown is here</div>
  </form>
</div>
<div class="page-content">
  <div class="sort-order-container">Here i need to drop it</div>
</div>

Of course I can use position:absolute; but how to make this dropdown relative to another div outside the form? Page content is flexible (pagination, banners etc.). It has to be physically inside the <form></form> to work, but I need to display (simulate display) it inside another div.

Upvotes: 1

Views: 986

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

Assuming that you are able to run Javascript without the same restrictions as with the editing of the HTML for the form then some very simple Javascript like this should suffice to move the select menu to the new location.

I put the relevant code within the setTimeout only so that the move is observable.

setTimeout(()=>{
  /* identify the various HTML elements needed in the move process */
  let form=document.querySelector('.left-sidebar > form');
  let target=document.querySelector('.page-content > .sort-order-container');

  /* Move the Select from original location (sidebar) to the new location */
  target.appendChild( form.querySelector('.move-this-outside') );

  /* set the ID of the form and associate the select with that form by ID */
  form.setAttribute('id','filter');
  target.firstElementChild.querySelector('select').setAttribute('form','filter');
},2500);
/*
  To show the select has moved
*/
.left-sidebar{border:1px solid red;}
.page-content{border:1px solid black;}
.sort-order-container{border:1px solid blue;}
select{background:pink}
h1{font-size:1.1rem}
*{padding:0.25rem;margin:0.25rem auto}
<div class="left-sidebar">
  <form>
    <h1>Select Menu was here</h1>
    <!-- source -->
    <div class="move-this-outside">
      <select>
        <option>Hello World
        <option>Goodbye World
      </select>
    </div>
  </form>
</div>
<!--

  other html content perhaps

-->
<div class="page-content">
  <div class="sort-order-container">
  <!-- target -->
  </div>
</div>

Upvotes: 2

Related Questions