简体   繁体   中英

How to use this variable to get the id of input in typeahead.js?

I am using typeahead for the first time and it should be an easy question for many of u. I have multiple input element for which i am using typeahead. All those elements have same class.

<input class="typeahead" type="text" id="element_1" >
<input class="typeahead" type="text" id="element_2" >

When typeahead is active on any element i need to determine it's id. This is what I am trying.

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
{
    name: 'items',
    displayKey: 'value',
    source:populateItems()
});


var populateItems=function(){
    return function findMatches(inp, cb) {
    console.log("id: "+$(this).id);   //this is where i need to find the id
    jQuery.get("auto_suggestion.php",function(data){
        // some work here ..
        cb(res);
    });
  };
};

I tried to see their examples and other sources on web but didn't find much help.

Try ...

$(this).attr("id");

... this uses jQuery, but get's the Id attribute using a quick, simple method that I use all the time.

You can't access element from data source function. this points to Dataset object, and there is no reference to input element. However you can initialize typeahead in each loop, so you can access current input element:

$('.typeahead').each(function() {
    $(this).typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'items',
        displayKey: 'value',
        source: populateItems(this.id)
    })
});


function populateItems (id) {
    return function findMatches(inp, cb) {
        console.log("id: " + id);
        // ...
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM