jQuery Tokeninput add if not exists
Asked Answered
C

8

19

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 found I want to add a new value so the next user will find it through autocomplete.

I found this great looking & easy to implement jquery plugin called TokenInput, but it doesn't seem to

accept entries that are not available in my database query.

Here's the link for the plugin: http://loopj.com/jquery-tokeninput/demo.html

Is there a workaround for this ? Or do you suggest another plugin that already has this feature.

And I'm a little bit concerned about the security aspect of this sort of websites is there something special I need to take care of when doing this sort of implementation ?

Chabot answered 24/9, 2011 at 14:35 Comment(1)
This solution worked for me. I am sure this will help. [1]: https://mcmap.net/q/665844/-populate-jquery-tokeninput-on-ajax-eventDiecious
T
13

When you enable tokenInput on a field,

$(selector).tokenInput(url, ...

that url is where tokenInput sends search queries. It points to a script which returns suggestions based on database entries matching the search query. What you want is to have that script add another suggestion to the list for that case when nothing in your database matches the search query. How to do this depends very much on the script.

Because you tagged your question with php, I'm guessing the url points to a php script which returns a JSON object full of suggestions. In that case, modify the php script so that it adds a new suggestion to the list:

"{id: " . $idForThisNewSuggestion . ", name: \"" . $searchQueryString . " (new suggestion)\"}"
Turfy answered 19/11, 2011 at 20:12 Comment(1)
good solution. you could also only show the searched term if no results are found to make it neaterDwight
F
17

This is now handled in the latest master of this plugin, using the allowFreeTagging option: https://github.com/loopj/jquery-tokeninput/blob/master/src/jquery.tokeninput.js#L57

The version number and docs haven't been updated in 2 years, so you'll have to use master.

Frugivorous answered 28/3, 2013 at 16:1 Comment(0)
T
13

When you enable tokenInput on a field,

$(selector).tokenInput(url, ...

that url is where tokenInput sends search queries. It points to a script which returns suggestions based on database entries matching the search query. What you want is to have that script add another suggestion to the list for that case when nothing in your database matches the search query. How to do this depends very much on the script.

Because you tagged your question with php, I'm guessing the url points to a php script which returns a JSON object full of suggestions. In that case, modify the php script so that it adds a new suggestion to the list:

"{id: " . $idForThisNewSuggestion . ", name: \"" . $searchQueryString . " (new suggestion)\"}"
Turfy answered 19/11, 2011 at 20:12 Comment(1)
good solution. you could also only show the searched term if no results are found to make it neaterDwight
B
10

Here's my solution with local json

$("#input").tokenInput(yourjsondata,{
    preventDuplicates: false,
    onResult: function (item) {
        if($.isEmptyObject(item)){
              return [{id:'0',name: $("tester").text()}]
        }else{
              return item
        }

    },
});

Everything with id:0 is a new entry

Bobbibobbie answered 3/3, 2013 at 16:39 Comment(3)
What/where is $("tester")? Do I need to create this separately?Isla
Figured it out, <tester> is a tag tokeninput adds the DOM to hold the text you're currently typing into the input box.Isla
Excellent solution +1Bellebelleek
E
2

To add to Shawn's answer (i.e. you need something server side to actually add it as a new item in the database), you might be able to make this change to allow the addition on the javascript side of things.

Eolic answered 20/11, 2011 at 8:16 Comment(0)
D
1

I also changed the onBlur function to select the first item if they click off the search box - its more intuitive to users:

.blur(function () {
        $(this).val("");
        if ($(".token-input-selected-dropdown-item").length>0)
            add_token($(".token-input-selected-dropdown-item").data("tokeninput"));
        hide_dropdown();
    })
Dwight answered 22/2, 2012 at 9:59 Comment(0)
Y
1
 $(document).ready(function() {
            $("#expert").tokenInput("source.php", {
                theme: "facebook",
                noResultsText:'Skill Not Found - Enter to Add',
                queryParam:'q',
                onResult: function (item) {
                                            if($.isEmptyObject(item)){
                                                  return [{id:$("#token-input-expert").val(),name: $("#token-input-expert").val()+'*'}]
                                            }else{
                                                  return item
                                            }
                },
                preventDuplicates:true<?php if($expert_rank_json){?>,
                prePopulate: <?php echo $expert_rank_json ?>
                <?php } ?>
            });
Youngran answered 14/4, 2014 at 21:20 Comment(0)
L
0

In the .php file, before the while condition, you can use this:

array_push($yourarray, array('id'=> 0 ,'name'=> $_GET["term"])); 
Laminar answered 6/3, 2013 at 11:34 Comment(0)
C
0

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');
        }
    }
});
Conservator answered 14/11, 2013 at 11:11 Comment(2)
What/where is $("tester")? Do I need to create this separately?Isla
Figured it out, <tester> is a tag tokeninput adds the DOM to hold the text you're currently typing into the input box.Isla

© 2022 - 2024 — McMap. All rights reserved.