2016-03-05 68 views
0

假设我有以下json对象,其中包含有关一组人的信息。通过属性搜索json对象的自动完成功能

data=[{id:2, fname:"bob", lname:"roberts", common_name:null, email:"[email protected]", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.339Z", updated_at:"2016-02-23T10:15:09.339Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}, 
     {id:1, fname:"John", lname:"Smith", common_name:null, email:"[email protected]", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.327Z", updated_at:"2016-02-23T10:15:09.327Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}] 

现在我想实现,通过每个人的名字搜索文本框某种自动完成功能(即fname+" "+lname)寻找匹配。在找到匹配时,它或者返回找到匹配的人或者该人的身份。

我在开始这件事时遇到了一些麻烦。我想我可以把它写出来,我用keyup来触发一个遍历对象的循环,显示匹配字符串的这些名字,并在点击其中一个时返回相应的索引,但这似乎是我重新发明了轮子。

是否有一种有效的/最佳实践的方式来拉这种功能?

+0

你可以尝试jQueryUI的自动完成功能... –

+0

你可以将所有FNAME +”“+ L-NAME在数组和提供它作为自动完成功能的来源 –

回答

1

从这个typeahead.js演示here

完整的代码上jsfiddle

var substringMatcher = function(strs) { 
    return function findMatches(q, cb) { 
    var matches, substringRegex; 

    matches = []; 

    substrRegex = new RegExp(q, 'i'); 

    $.each(strs, function(i, str) { 
     var fullname = str.fname + " " + str.lname 
      console.log(fullname); 

     if (substrRegex.test(fullname)) { 
     matches.push(fullname); 
     } 
    }); 

    cb(matches); 
    }; 
}; 
+0

嘿,谢谢你的回应和小提琴。当我选择值(即来自对象的id)时,我最终有兴趣从自动完成中获得其他属性。我该怎么做? – neanderslob

+0

我不知道我是否了解你,你可以举一个例子 – irfan

+0

如果你想达到所选人的ID:https://jsfiddle.net/refan/a62vuceu/4/ – irfan

相关问题