You are quite close to the working solution. I propose the following changes:
Instead of testing for regex, simply split on commas: The plugin you are using puts a comma automatically after each new selected value. Therefore, you can simply count the number of values by the number of commas. As an example:
function checkReceiver() {
var str = document.forms[0].tags.value;
var words = str.split(','); // split on commas
var count = words.length - 1; // a correction for the first element
document.forms[0].receiver.value = count;
}
Alternatively, you could also split on spaces:var words = str.split(' ');
, if you think that users might delete the last comma. Splitting on spaces assumes at least a space between two values.
Make sure that the function is called on any change: To make sure that the checkReceiver()
function is called at any possible change, you need to make sure that it captures all events. One way of capturing the events in the <input>
element is by forcing a check upon any possible change. As an example (method from the comments in this answer):
<input type="text" name="numbers" id="tags" class="input_text clearable" size="50"
onchange="checkReceiver();"
onkeypress="this.onchange();"
onpaste="this.onchange();"
oninput="this.onchange();"
placeholder="Choose Receiver" tabindex="1" value="" autofocus>
Additionally, you also want to call checkReceiver()
when the autocomplete list closes. Therefore:
.autocomplete({
close: function(event, ui) {
checkReceiver(); // call checkReceiver() upon close
}, ...
With these changes in place, the program works as expected. See this jsFiddle.
I can also recommend you to take a look at jQuery Tokeninput which is specifically designed for multiple-input autocomplete text entries, and works in a very intuitive manner. For example, with Tokeninput you can use the onAdd and onDelete Callbacks (see here). With these callbacks, you can then simply increase (onAdd) and decrease (onDelete) a counter variable.