0

I have an input field. And I want that it shows the (...) at the end of my text when I hit a specific number of characters.

I heard something about Substring but I don't know how to use it.

Here is my Input field. The data-limit shows at which point the text is to long.

    <input class="controlinput" id="metadescription" data-limit="156"  data-class=".metadescription" type="text" >

And here is where the text will display when I type it in the input field.

<span class="metadescription"> </span>
Razia sultana
  • 2,168
  • 3
  • 15
  • 20
Leon
  • 27
  • 6

2 Answers2

1
document.getElementById('yourInput').addEventListener('input', function(){
  var val = document.getElementById('yourInput').value
  if(val.length === 156){
    document.getElementById('yourInput').value = val + '(...)';
  }
})

if you add an eventhandler for change event of the input field you can check how long is the added string and if it reaches the given length you can add the string you want to

fiddle: https://jsfiddle.net/a623p30u/

lacexd
  • 903
  • 1
  • 7
  • 22
  • 1
    Not 100% working. Once you reach the 156 limit, it would then be 161 and the input would accept characters to be appended after (...) because of the explicit check of 156. – Steve Dec 12 '16 at 15:03
  • 1
    you are right, but i was lazy to solve the whole problem, i think its a good way to start – lacexd Dec 12 '16 at 15:20
  • yes, it is not working out of box, you need to change it a little bit to match your needs – lacexd Dec 12 '16 at 15:41
  • could you please post your changes? – lacexd Dec 12 '16 at 15:44
  • document.getElementById('#metadescription').addEventListener('change', function(){ var val = document.getElementById('#metadescription').value if(val.length === 156){document.getElementById('#metadescription').value + '(...)'} }) – Leon Dec 12 '16 at 15:46
  • it is because you assign a new value to nothing, i change my answer – lacexd Dec 12 '16 at 15:48
  • i!ve updated my answer with a jsfiddle link, for me it was working like this – lacexd Dec 12 '16 at 16:31
0

sources:
http://www.w3schools.com/jsref/jsref_substring.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

var input = $('.controlinput');
var inputLength = input.val().length
var maxLength = input.data('limit');
var mustTruncate = inputLength > maxLength;
if(mustTruncate){
  var truncatedValue = input.val().substring(0, maxLength) + "(...)";
  var label = $("."+input.data("class"));
  label.html(truncatedValue);
}
Brian H.
  • 854
  • 8
  • 16