2014-02-13 22 views
6

我試圖實現標記 - 它的輸入,但我想限制用戶只從自動填充框中選擇 值。 我嘗試使用源json來overTenderTagAdded事件,並檢查源代碼中是否存在標記 但沒有運氣。jQuery標記 - 它只允許來自自動完成源的標記

這是代碼,請參閱beforeTagAdded函數。

 $(document).ready(function() { 
     var itemId; 
     var theTags = $('#msg_to'); 
     theTags.tagit({ 
      autocomplete: { 
       source: [{ id: "1", value: 'David'}, { id: "2", value: 'John' }], 
       minLength: 0, 
       select: function (event, ui) { 
        itemId = ui.item.id; 
        theTags.tagit("createTag", ui.item.value); 
       } 
      }, 
      showAutocompleteOnFocus: true, 
      afterTagAdded: function (event, ui) { 
       if (itemId) { 
        $(ui.tag).find('input').attr('name', "tag[\'" + itemId + "']['" + ui.tagLabel + "']"); 
        itemId = null; 
       } 
      }, 
      beforeTagAdded: function (event, ui) { 
       var id = ui.autocomplete.source; // not working 

      // what to do next? 
      } 
     }) 
    }); 
</script> 

在此先感謝

回答

1

還有的標籤 - 它叉子會做你想要什麼:

https://github.com/chrisleishman/tag-it

它有一個requireAutocomplete設置。

(我不得不那種合併兩個版本,因爲我需要的東西,從各...但我希望這會幫助你。)

+0

謝謝所有,我發現使用select2更容易使用。 –

2

對我來說,以下工作:

var currentlyValidTags = []; 
$('#tags').tagit({ 
    autocomplete: { 
    source: function(req, resp) { 
     search(req, function(data) { 
     currentlyValidTags = data; 
     resp(data); 
     }); 
    } 
    }, 
    beforeTagAdded: function(event, ui) { 
    if (!_.contains(currentlyValidTags, ui.tagLabel)) { 
     return false; 
    } 
    } 
}); 

以上解決方案與版本2.0一起工作在65d6fb4dad833bf490f2a7b27063ecd08f792ede(與標籤v2.0上的版本2.0不同)。

5

我的解決辦法:

$(function() {  
    var currentlyValidTags = ['ac', 'dc']; 
    $('input[name="_tags"]').tagit({ 
    availableTags: currentlyValidTags, 
    autocomplete: { source: function(request, response) {   
     var filter = removeDiacritics(request.term.toLowerCase()); 
     response($.grep(currentlyValidTags, function(element) { 
         return (element.toLowerCase().indexOf(filter) === 0); 
        })); 
    }}, 
    beforeTagAdded: function(event, ui) { 
     if ($.inArray(ui.tagLabel, currentlyValidTags) == -1) { 
     return false; 
     } 
    }   
    });  
}); 
0

如果您是通過AJAX尋找自動完成,這裏是一個解決方案。

//this will be set true only if fetched via ajax and also selected from autocomplete 
$.is_ajax_fetched = false; 

autocomplete你需要這些事件內幕:

select: function(event, ui) { 
$.is_ajax_fetched = true; 
return true; 
}, 

//select event will not work alone as tag-it captures event to check for comma and other stuff  
close: function(event, ui) { 
if($.is_ajax_fetched == true){ 
$('.ui-autocomplete-input').blur(); 
$('.ui-autocomplete-input').focus(); 
} 
} 

現在在標籤調用它,你將需要添加呼叫事件中的選項:

beforeTagAdded: function(event, ui) { 
    if($.is_ajax_fetched != true){return false;} 
}, 

afterTagAdded: function(event, ui) { 
    $.is_ajax_fetched = false; 
},