0

I have a function to get the value of an element when clicked, I would then like to use that to match which array to use in a bootstrap typeahead later in the script. so for example:

var use = [];

$('.dropdown-menu > li > a').on("click", function() {
    use = $(this).data('name');
    alert(use);
});

if the data-name attribute selected is "cat" than the "use" variable would equal "cat" and we have a "cat" array:

var cat = [
    {val: 'res', string: "Residential"},
    {val: 'Dup', string: "Duplexes & Apartments"},
    {val: 'Con', string: "Condominiums"},
    {val: 'Lot', string: "Lots, Land & Farms"},
    {val: 'Com', string: "Commercial"},
    {val: 'Mob', string: "Mobile Homes"},
];

and then this is where I am not sure how to handle this. instead of using "cat" in the below function, I would like to replace "cat" with whatever function matches what is data-name selected above.

$('#input-tag').typeahead({
    source: function(query, process) {
            var results = _.map(cat, function(value) {
                return value.val;
            });
            process(results);
    }
});

I hope I explained this right. I think I'm a bit over my head tonight!

1 Answer 1

1

You can create an object where the key is the data source(e.g. cat) and the value is an array:

var obj = {
   "cat" :  [
    {val: 'res', string: "Residential"},
    {val: 'Dup', string: "Duplexes & Apartments"},
    {val: 'Con', string: "Condominiums"},
    {val: 'Lot', string: "Lots, Land & Farms"},
    {val: 'Com', string: "Commercial"},
    {val: 'Mob', string: "Mobile Homes"}
],
   "dog": [ {val: 'res', string: 'Dunno' }]
};

And then you can fetch the correct array this way:

var data = $(this).data('name'); // 'cat';
var catArr = obj[data];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked perfectly. Coincidentally cat is short for category lol ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.