Hello,

I am trying to restrict to maximum type 60 words in a textbox.
I have tried to put a code that check if we have more than 60 words.

The code restricts to 60 words but when I loop the textboxes words and put back the string (up to 60 words) the string says:

"undefined undefined undefined undefined... etc"

Why does this happen? what is undefined?

 <asp:TextBox ID="TextBox26" runat="server" Height="209px" TextMode="MultiLine" onkeyup="return countwordsarticle();"
                Width="650px" Font-Names="Arial" Font-Size="10pt" ForeColor="#333333"></asp:TextBox>


    function countwordsarticle() {

        var str1 = document.getElementById("TextBox26").value.replace("  ", " ").trim();
        var words1 = str1.split(' ').length;

        //If more than 60 words only show 60
        if (words1 > 60) {

            var newstr;
            for( var i = 0; i < 60; i++ )
            {
                newstr = newstr + words1[i] + " ";
            }

            //Put to textbox
            document.getElementById("TextBox26").value = newstr.toString();
        }

        return false;
    }

Recommended Answers

All 5 Replies

This is the Java forum.
That's not Java code.

Hi

You are setting words1 to the length, change it to:

var words1 = str1.split(' ');

Then change your if statement to:

if (words1.length > 60)

Also you should probably initialise newstr with:

var newstr = "";

Also a note on style. Don't use variable names like words1 and newstr - make variable names describe what they are for. It will make it easier for other people and yourself to understand and work with.

Hopefully that makes sense?

Member Avatar for stbuchok

If this is being saved to a database and the field is set to something like nvarchar(255), this could cause errors as 60 words can be more than 255 characters. If the field is nvarchar(max) then there is no need to set a limit at all (unless you are worried about space or attacks I guess). TextBox26 is not a useful name for a textbox, it does not describe it's contents or purpose. trim is not a builtin JavaScript function, so unless you are extending something like the String prototype, this will cause an error. Also, just counting spaces will be inaccurate as older people (sorry to single out the older people) tend to put two spaces after a period (which is no longer relavent), or any other doulbe spacing. If you search Google for "Regex to count words", you should find some examples that will give a more accurate count. Hope this helps.

Thanks DaveAmour,

You solved the problem perfectly! :)
I was doing the wrong thing with the .length there. So I removed it and it was correct.

Thank you!

Happy to help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.