Code Demon Code Demon - 28 days ago 6
Javascript Question

adjust the width of the input that correspond to the value length of the input

I'm trying to make an auto resize like input, like when the user type in, the input will adjust automatically to fit the value inside the input but seem's I can't make it right or working. Any ideas, help please?



$(document).ready(function(){
$('input').on('input',function(){
$(this).css('width',$(this).width()+$(this).val().length );
});
});

input{border:1px solid red;width:30px;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<input type="text">




Answer

If your goal is for it to be just as wide as necessary, maybe with a 30px buffer, then the issue is you're adding to the width every time rather than recalculating it from scratch. It would also help if you knew how wide a character might be, so probably best to set the font size specifically or even use another hidden element to measure how wide the rendered text is; here I use a span for that:

$(document).ready(function(){
  $('input').on('input',function(){
    var $this = $(this);
    // Get the value
    var val = $this.val();
    
    // Put it in the hidden span using the same font information
    var $hidden = $(".hidden");
    $hidden.text(val);
    
    // Set the input to the span's width plus a buffer
    $this.css('width', $hidden.width() + 30);
  });
});
input {
  border:1px solid red;
  font-size: 14px;
  width:30px;
}
.hidden {
  font-size: 14px;
  display: none;
}
<input type="text">
<span class="hidden"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments