1

I want to prevent users to enter Space key in input[type='text'] when it is empty. And if its not after entering Space key the value of input[type='text'] should be grabbed and put it in a span tag. Now i want to assign a for-loop to do the second part(I mean put value in span) only five times. And when 5 span already exist.Don't do this any more. where should I add my for-loops? here is my code:

$(function() 
   {
        $("#tags-selected").on('keypress', function(e) 
        {
                var tags_selected=$("#tags-selected").val();    
                if(e.which === 32)
                {
                    if(!this.value.length)
                        e.preventDefault();
                    else
                        $("<span class='suggested-tag'>"+tags_selected+"<span class='closee'>XX</span></span>").insertBefore("#tags-selected");
                        $("#tags-selected").val('');
                        $(".tags-review").fadeOut(300);

                } 

        });
    }); 
2
  • 1
    Don't you think you need to use trim while checking this !this.value.length, like this !this.value.trim().length, otherwise it will count blank space and will never satisfy your first condition? Commented Sep 28, 2016 at 7:57
  • 2
    it's your responsibility to check answers on your each question and mark and up-vote the correct answer.Thanks Commented Sep 30, 2016 at 6:41

1 Answer 1

5

You don't need to add loop for that. Just check for the length of appended span elements with class suggested-tag. and only append new element if length is less than 5:

if($('span.suggested-tag').length < 5){
   $("<span class='suggested-tag'>"+tags_selected+"<span class='closee'>XX</span></span>").insertBefore("#tags-selected");
   $("#tags-selected").val('');
   $(".tags-review").fadeOut(300);
}
Sign up to request clarification or add additional context in comments.

Comments

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.