Home > Software engineering >  User defined positioning on a grid of html form fields
User defined positioning on a grid of html form fields

Time:06-09

I have a form with some input elements that I want to arrange on a grid according to users' preferences. Looking around I have come across CSS grids.

I am thinking about creating a CSS grid with r rows and c columns, and then using javascript to assign input elements to the grid's cells according to a user defined layout (for example, an object having the id of the input elements as keys and the (column-span) pairs as values).

I don't know if this is the best (or even a viable) solution, and it sounds like a lot of boilerplate code to change the CSS properties of the input elements. So my questions are: is this the right approach to this problem? Are there other (better, easier) approaches, not necessarily based on CSS grids?

I am using plain javascript and Vue.js, if it matters (sorry for my imprecise wording, I am a hobbyist, self-taught developer).

CodePudding user response:

you can set an attribute to the input or any html tag.

If the ordering based on user-preferences, then I assume you will have a json object that tells the position of the fields in the form, so you can set an attribute to the html tag

<span data-column="0" data-row="0" />
<input type='text' data-column="1" data-row="0" />
or 
<input type='text' data-order="1:0" />
<input type='text' data-order="0:0" />

then when generating the form with a loop statement, you can then getAttribute/setAttribute with document.getElementById().setAttribute('attrName','attrValue')

CodePudding user response:

You can use grid-template-areas to assign elements to a position in the grid irrespective of their order in the DOM.

form {
  display: grid;
  gap: 0.5rem;
  grid-template-areas: "w x" "y z";
}

#a { grid-area: z; }
#b { grid-area: w; }
#c { grid-area: y; }
#d { grid-area: x; }
<form>
  <input id="a" type="text" placeholder="A">
  <input id="b" type="text" placeholder="B">
  <input id="c" type="text" placeholder="C">
  <input id="d" type="text" placeholder="D">
</form>

  • Related