2

I am trying to limit keyword input.

Whenever a user enter a keyword, it will append 'span' to that keyword, e.g.

like the html code below.

I can limit words, but the count is not accurate but when it reach 5, it stop entering.

If I refresh page, I can enter one more again, then stop me again too.

The weird things, it doesn't work if I use id for var count=$('#result_tag').text(). I have to use class.

I had tried to change /\S+/g to /\s+/g, not working, I have to keep S capital.

JQuery:

$( "#tag" ).on( "keydown", function( event ) {

        var count=$('.result_tag').text();
        var words=count.match(/\S+/g).length;

        if(words >= 8 ){

            alert('No more than eight words');  
        }       

        //save tag after press enter key   
        else if ( event.which==188 || event.which == 13 ) {

        event.preventDefault();
        //codes will do the action

HTML:

<span id="result_tag" class="result_tag">keyword that user enter</span>
<span id="result_tag" class="result_tag">keyword that user enter</span>
<span id="result_tag" class="result_tag">keyword that user enter</span>
1
  • 3
    You cannot have same ID's. Commented Feb 20, 2015 at 5:15

2 Answers 2

4

ids should be unique, that's why "it doesn't work if I use id".

As for your other problem, your method of counting seems a little convoluted. Sounds like all you need to do is count the spans themselves:

var words = $('.result_tag').length;

Sign up to request clarification or add additional context in comments.

Comments

1

Use length property to get the count of keywords.

    $("#tag").on("keydown", function(event) 
    {
         var count = $('.result_tag').length;
         if (count >= 8) 
         {
               alert('No more than eight words');
         }

         ...........
         ...........

1 Comment

FYI: The .size() method is deprecated as of jQuery 1.8. Use the .length property instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.