I have a form with text boxes that can vary widely in size. I'm trying to resize them based on their contents.
I've been working with various solutions, and I've boiled it down to this:
$("input[type=text]").width($(this).val().length)
It seems to me that this should work. Can someone please tell me why it doesn't? Thanks.
It works but by default using .width(parameter) automatically converts the parameter to pixels. So using .length will give you 1 character = 1 pixel only.
Try the demo below, I've added another input field that uses multiplication to further add/specify length for each character input;
$("input[type=text]").on("keypress", function() {
$(this).width($(this).val().length);
});
$("input[type=text].add").on("keypress", function() {
$(this).width($(this).val().length * 8);
});
input {
margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Default" />
<br/>
<input class="add" type="text" placeholder="With Multiply" />