jQuery Tokeninput add if not exists

前端 未结 8 729
野的像风
野的像风 2021-02-05 09:07

I am in the process of writing a script that builds upon user input,

I have some fields that its values need to be quired from the database,

and if no entry fo

8条回答
  •  礼貌的吻别
    2021-02-05 09:16

    I have added some functionalities to SteveR's answer, because I wanted the value to appear at the top of the dropdown even if there are results. Also onAdd if the item selected does not exist in the databese I want to add it:

     $("#my_input").tokenInput(my_results_route), {
        hintText: "Select labels",
        noResultsText: "No results",
        searchingText: "Searching...",
        preventDuplicates: true,
        onResult: function(item) {
            if($.isEmptyObject(item)){
                return [{id:'0', name: $("tester").text()}];   
            } else {
                //add the item at the top of the dropdown
                item.unshift({id:'0', name: $("tester").text()});
                return item; 
            }
        },
        onAdd: function(item) {
            //add the new label into the database
            if(!parseInt(item.id)) {
                //database insertion ajax call
                console.log('Add to database');
            }
        }
    });
    

提交回复
热议问题