Set input fields width to allowed width

Default all input widgets will display at 100% width. Changing it to auto will make them all the same smaller size. I know you can use lay-out grid columns to force widths, but that's still a hardcoded solution.   Is there a way to set the width depending on the max allowed characters? So a field with max 2 characters will be very small and a field with max 200 characters would probably stretch out 100%.
1 answers

When you set the maximum length property for the field on the page, your fields will get the attribute maxlength available.

This property can be used in a javascript action like below:

var ele = document.getElementsByClassName('form-control');
for (var i = 0; i < ele.length; i++ ) {
var elewidth = ele[i].getAttribute('maxlength');
    ele[i].style.width = elewidth+'%';

This is just a simple example that retrieves all elements with the class form-control.

Loops over the elements and set the width of the fields to the maxlength as percentage.

Of course you’ll need some more calculation on the width needed, but this little piece of code might help you further in finding a fitting solution for your case.

The other option would be to define classes and assign these to the fields when there aren’t that many different field sizes (length constraints) this seems to be the better option.