Reputation: 315
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.
Upvotes: 1
Views: 1219
Reputation: 1
If you calculate the width based on text length, the solution can be broken when entering some characters which have different size. Like: w
vs i
.
My suggestion: Get the value from the input, add it to some div which is hidden on the <body>
tag. After calculating the text width based on the div, you can update the input width.
$("input[type=text]").on('input', function (event) {
var value = $(this).val();
var div = $('<div>').text(value).appendTo('body');
$(this).width(div.width());
});
div {
position: absolute;
visibility: hidden;
font-size: 12px;
font-family: Arial;
}
input {
padding: 0 6px;
font-size: 12px;
font-family: Arial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" />
Note: The font-size
and font-family
properties of the div/input must be the same.
Upvotes: 2
Reputation: 6130
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" />
Upvotes: 2