Broshi
Broshi

Reputation: 3622

jQuery truncate text by CSS overflow

I want to truncate the input value by the available space for letters on the screen.

For example, if my input field can contain only 5 letters and after that the input 'scrolls' to the right (overflow) I want jQuery to limit only to 5 letters because that's the available and visible space to the user.

Bottom line - I want jQuery to truncate to the visible letters according to the input's overflow and remove the letters which are not visible.

Example:

enter image description here

I want jquery to truncate the text only to Lorem Ips although the value is actually Lorem Ipsum

How can I do that?

Upvotes: 1

Views: 115

Answers (2)

Kiran Shakya
Kiran Shakya

Reputation: 2569

I have a snippet ready as you requested, thanks for the author of this codepen snippet

If you think this answer as helpful, please give some credit to the author of above codepen snippet too.

///////////////////////////////////////////////
// Source: https://codepen.io/Momciloo/pen/bpyMbB
///////////////////////////////////////////////
$.fn.textWidth = function(text, font) {

  if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);

  $.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));

  return $.fn.textWidth.fakeEl.width();
};
///////////////////////////////////////////////

$("input").on("input", function(e) {
  var tWidth = $(this).textWidth(),
      cWidth = $(this).width();
  if (tWidth > cWidth) {
    $(this).val($(this).data("val"));
  } else {
    $(this).data("val", $(this).val());
  }
});
input {
  clear: both;
  float: left;
}

.i1 {
  width: 12em;
}

.i2 {
  width: 6em;
}

.i3 {
  width: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="i1" />
<input type="text" class="i2" />
<input type="text" class="i3" />

Upvotes: 0

Nanhe Kumar
Nanhe Kumar

Reputation: 16307

$(document).ready(function(){
    $("#id_of_textbox").attr('maxlength','5');
});

Upvotes: 1

Related Questions