views:

151

answers:

2

Hi there,

I have the following code and what I am trying to do is set up an Autocomplete input box that when it is filled out, create another autocomplete input box underneath it.

  • The problem with my code is that since I am using blur, it will create a new input every time I click off of the first one.

  • The second problem is that I need to setup the autocomplete on the newly created input box, but if I do it recursively then it will crash.

Code:

function setupAutoComplete()
{
 var autoCompleteData = $("#listContacts").html().split("<br>");
 //autoCompleteData = replaceAll(autoCompleteData, "&lt;", "<");
 //autoCompleteData = replaceAll(autoCompleteData, "&gt;", ">");
 $("[name|=toemail[]]").autocomplete(autoCompleteData);
 $("[name|=toemail[]]").result(function(event, item) {
    $("[name|=toemail[]]").blur();
 });
 $("[name|=toemail[]]").blur(function(){
  var newString = $(this).val();
  newString = replaceAll(newString, "&lt;", "<");
  newString = replaceAll(newString, "&gt;", ">"); 
  $(this).val(newString);
  var newfield = '<p><label class="" disabled="true"><select name="toSelect[]"><option>To: </option><option>CC: </option><option>BCC: </option></select></label><input type="text" value="" name="toemail[]" /></p>';
  $("#composeTo").append(newfield);
 });
}
+1  A: 

Rather than setting up the auto complete on the elements as a group you should be doing it individually as each one is created. This will stop the recursion.

Secondly to avoid the onblur event firing when you click somewhere else on the screen you should catch the tab key being pressed on a keypress.

mjmcloug
A: 

Posting my own solution.

function setupAutoComplete()
{
    var autoCompleteData = $("#listContacts").html().split("<br>");


$("[name|=toemail[]]").each(function(key, value) {
    if (!($(this).hasClass("blurred")))
    {
    $(this).autocomplete(autoCompleteData);
    $(this).result(function(event, item) {
        var newString = $(this).val();
        newString = replaceAll(newString, "&lt;", "<");
        newString = replaceAll(newString, "&gt;", ">"); 
        $(this).val(newString);
        $(this).blur();
    });
    $(this).blur(function(){
        if (!($(this).hasClass("blurred")))
        {
        var newfield = '<p><label class="" disabled="true"><select name="toSelect[]"><option>To: </option><option>CC: </option><option>BCC: </option></select></label><input type="text" value="" name="toemail[]" /></p>';
        $("#composeTo").append(newfield);
        setupAutoComplete();
        $(this).addClass("blurred");
        }
    });
    }
});
Gazler