1

I try to cut a too long text and replace it with "...".

HTML:

<div class="test">    
    <span>Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</span>
</div>

Jquery:

$.each($('.test span'), function(key, testName) {
    var curText = $(testName).text();
    $(this).attr('title', curText);
    var lengthToShortenTo = Math.round(parseInt($(this).parent('.test').css('width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text(curText.substring((curText.length - lengthToShortenTo), curText.length) + '... ');
    }
});

The output of the shortened span is:

select option that has a fixed width adding more...

But I want to get the first part of the text and not the last. So this is what I want too get:

Item text goes in here but it is way too long...

Demo: http://jsfiddle.net/jNWS6/247/

3 Answers3

3

Why not just use CSS?

.test {
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

Demo

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

I think you just need to change this line

$(this).text(curText.substring((curText.length - lengthToShortenTo), curText.length) + '... ');

to this

$(this).text(curText.substring(0, lengthToShortenTo) + '... ');

R.

Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34
1

you are taking wrong part of substring, you should take first part

$.each($('.sedcardHolder span'), function(key, sedcardName) {
    var curText = $(sedcardName).text();
    $(this).attr('title', curText);

    var lengthToShortenTo =     Math.round(parseInt($(this).parent('.sedcardHolder').css('width'), 10) / 5.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text(curText.substring(0,(curText.length - lengthToShortenTo)) + '... ');
    }
});
Murat Güvenç
  • 111
  • 1
  • 5