Reputation: 111
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);
}
});
});
Upvotes: 1
Views: 67
Reputation: 82231
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);
}
Upvotes: 5