Reputation: 2094
I'm working on an application where you can click on user names to add them to the reply list. If the username is already added, it doesn't add their username again. The problem I'm having is that if the user @assassin is added, and I try to add the user @ass, it finds @ass-assin and thinks that @ass is already added. Here's my code:
$('#mentions a.mention_user').live('click', function(e){if($('textarea#message').val().toLowerCase().search('@'+$(this).text().toLowerCase()) < 0){
$('textarea#message').val('@'+$(this).text()+' '+$('textarea#message').val());
}
e.preventDefault();
});
Thanks in advance!
EDIT: The text it'll be matching the usernames against will look similar to this: @user @joe @adam this is a message @someone
Upvotes: 2
Views: 1453
Reputation: 150010
Assuming that the separator is always a space character, you can do this:
$('#mentions a.mention_user').live('click', function(e){
var taMsg = $('#message'),
userName = '@'+$(this).text()+' ';
if( (taMsg.val().toLowerCase() + ' ').indexOf(userName) != -1) {
taMsg.val(userName + taMsg.val());
}
e.preventDefault();
});
The idea is if you add a space to the end of the list of usernames then you can search it for a particular username with a space after it.
I've also updated the code to cache the jQuery object for the message textarea, rather than repeating it three times. Note that if you are selecting with an id like '#message' then (given that id is unique) you don't need the 'textarea' prefix.
Also since you're not actually using a regex I've switched to .indexOf()
instead of .search()
.
Upvotes: 0
Reputation: 6208
Assuming the space character is illegal for usernames. Split the textarea message string into arrays delimited by space and check each array element against the proposed username.
$('#mentions a.mention_user').live('click', function(e) {
if ($.inArray('@'+$(this).text(),$('textarea#message').val().split(' '))) {
$('textarea#message').val('@'+$(this).text()+' '+$('textarea#message').val());
}
e.preventDefault();
});
Upvotes: 2
Reputation: 3829
Bit hard to test without your full code, but searching by Regular Expression, and making sure it has a character that isn't A-Z, a-z, 0-9 (and any other valid username character) after it might do the trick.
Something like:
$('#mentions a.mention_user').live('click', function(e){if(($('textarea#message').val().toLowerCase() + ' ').search(
new RegExp("'@'+$(this).text().toLowerCase() + '[^A-Za-z0-9\-_]')
) < 0){
$('textarea#message').val('@'+$(this).text()+' '+$('textarea#message').val());
}
e.preventDefault();
});
Upvotes: 0
Reputation: 718
Compare the length of the item being added to the length of the item matched. If the lengths are equal, the item being added is already there.
Upvotes: 0