Display only 10 characters of a long string?

前端 未结 12 2093
臣服心动
臣服心动 2020-12-13 01:19

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?

Sorry guys I\'m a novice at JavaScript & JQuery :S

12条回答
  •  遥遥无期
    2020-12-13 02:05

    And here's a jQuery example:

    HTML text field:

    
    

    jQuery code to limit its size:

    var elem = $("#myTextfield");
    if(elem) elem.val(elem.val().substr(0,10));
    

    As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:

    $(document).ready(function() {
        var elem = $("#myTextfield");
        if (elem) {
            elem.keydown(function() {
                if (elem.val().length > 10)
                    elem.val(elem.val().substr(0, 10));
            });
        }            
    });
    

    Update: The above code snippet was only used to show an example usage.

    The following code snippet will handle you issue with the DIV element:

    $(document).ready(function() {
        var elem = $(".tasks-overflow");
        if(elem){
            if (elem.text().length > 10)
                    elem.text(elem.text().substr(0,10))
        }
    });
    

    Please note that I'm using text instead of val in this case, since the val method doesn't seem to work with the DIV element.

提交回复
热议问题