How to limit the characters of a label?

Asked

Viewed 950 times

2

I’m in an e-commerce project, and I need to display a product name. I’m thinking of using a label for this. The idea is to leave x characters visible, if the title exceeds this number x of characters, display "...". I don’t know how to do this, nor if the best option or if it is possible with a label.

Remarks: I am using jsp to recover the product title of the database. The programming language is JAVA and use html and jsp. I can recover the name with <%anuncio.getTitulo()%>.

Any tips or suggestions on how to do this?

  • If I understand correctly, when the title of the ad you’re picking up through the <%anuncio.getTitulo%> outnumber X of letters will be displayed ... in the title, that?

  • If that’s what you want to do, play your get back <%anuncio.getTitulo%> within a string variable and use the method length() that returns the number of letters of a variable String, make a condition, if this number returned exceeds the number of letters you want just have display ... else displays <%anuncio.getTitulo%> even

3 answers

3


Java Servlet 3.0 or higher

If you are using Java Servlet version 3.0 or higher you can use this code snippet:

<lable><c:out value="${anuncio.getTitulo().length() <= maxSize ? anuncio.getTitulo() : anuncio.getTitulo().substring(0, maxSize).concat('...')}" /></lable>

maxSize is the maximum size you want on the label.

If you will use this in various locations, create a tagfile is a good option.

Java Servlet lower than version 3.0

Another option, if you are using a version below Java Servlet 3.0 is to use the following scriptlet:

<label>
    <%
        int maxSize = 5;
        String titulo = anuncio.getTitulo();
        out.println(titulo.length() <= maxSize ? titulo : titulo.substring(0, maxSize).concat("..."));
    %>
</label>
  • It worked with the second option. Thank you!

2

You can also make this approach using only HTML and CSS:

label{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-wrap: hyphenate;
    max-width: 100px;
    display: block;
}
label > span{
  overflow: hidden;
}
<label>
  <span>
    Isso é um texte com um label muito grande
  </span>
</label>

Hug

0

I don’t know how to do this in jsp, but in direct javascript in html would be the following:

in js:

<label id="label">Estou num projeto e-commerce, e preciso exibir o nome de um produto</label>


(function(){
var element = document.getElementById("label");
element.innerHTML  = 
                        //@inicio, //@comprimento
 element.innerHTML.substr(0, 10)+"...";
})()

The code replaces the element text with its own "broken" text in a number x of characters (including spaces) and concatenates with "..."

https://jsfiddle.net/a5r375eb/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.