Let us consider i am having a text box where i can enter user names separated by commas.
EDIT: In Detail:
I am having a text box and a search_button nearby.
When i click on the search box list of users will be displayed there in a popup with a check box nearby
When the user the clicks the check box and clicks submit the corresponding users name will be displayed on the text box.
My problem is: I should not able to add the user name twice. That is when i click on the same user which i added already, it should throw an alert message a开发者_StackOverflow社区nd that corresponding name should not be added in the text box.
My code for this is given below:
var res_user = '';
// checked username will get
var existing_names = $('#text_box').val();
$('#popups input[type="checkbox"]:checked').each(function() {
res_user = res_user + $(this).parent().next().attr('value') + ', ';
});
if ($("#text_box").length > 0) {
target = $("#text_box").val($("#text_box").val() + ' ' + res_user);
}
Drupal.popups.close();
return false;
How can this be done using Jquery.
Any help will be thankful and grateful....
Thanks in advance...
You can use this code. It puts all the newly selected users into an array. Then, it loops through that array, makes a regular expression out of each name and looks for that regex in the comma separated list. If it's found, then we don't add this one. If it's not found, we add it.
var selectedUsers = [];
// checked username will get added to selectedUsers array
$('#popups input[type="checkbox"]:checked').each(function() {
selectedUsers.push($(this).parent().next().attr('value'));
});
var currentUsers = $("#text_box").val();
var regex;
for (var i = 0; i < selectedUsers.length; i++) {
// make regex for this selectedUser so we can search to see if it's already there
regex = new RegExp("(^|, )" + selectedUsers[i] + "(,|$)", "i");
// if this username not found in the current string, then we can add it
if (currentUsers.search(regex) == -1) {
if (currentUsers.length != 0) {
currentUsers += ", ";
}
currentUsers += selectedUsers[i];
}
}
// put updated user list back in the textbox
$("#text_box").val(currentUsers);
You can see a slightly modified version with my own HTML work here: http://jsfiddle.net/jfriend00/du6UF/.
Try using this function in your script tag:
$(function(){
$('#TextBox').change(function() {
var $current = $(this);
if ($(this).val() == $current.val()
{
alert('duplicate found!');
}
});
});
精彩评论