$('input').on('input', function () {
$(this).attr('size', $(this).val().length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" size="0">
When the input renders, it should have 0 width, and when it has no text in it, it should have 0 width.
Instead it takes on default width. size attribute works correctly for all sizes greater than 0.
How can I get a 0 size attribute on an input elmeent to be rendered like 0 width by the browser?
in this case I would recommend you to use style='width: 0ch'. The length of the field will be the size of one char:
$('input').on('input', function () {
$(this).css('width', $(this).val().length + 'ch');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width: 0ch'>
You can use a CSS attribute selector to apply width: 0px to all input elements where the size attribute is 0.
$('input').on('input', function() {
$(this).attr('size', $(this).val().length);
})
input[size="0"] {
width: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" size="0">
Although you'd be better off setting its width to 0px onload for syntactically valid HTML:
$('input').on('input', function() {
$(this).attr('size', $(this).val().length);
}).width(0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" size="0">