Question

I'm making a simple iPhone web page that lists around 200 medical terms and their definitions. I'm using JQuery autocomplete to allow the user to dynamically search the terms, and when they tap the term they want I want to display the term's definition right below. I need help setting up a JS array with both the term and the definition at once.

Currently, I have an array loaded as such :

var terms = [
        "Abdomen",
        "Ability",
        "Abolish",
etc...

What I would prefer however is if I knew how to load a term and its definition in an array like this:

terms['Abdomen'] = 'stomach, stomach area, belly, tummy';
terms['Ability'] = 'skill';
terms['Abolish'] = 'end, do away with, get rid of';

Anyway, at the end of the terms array list I activate the autocomplete code as such:

$( "#terms" ).autocomplete({ source: terms,});
    $( "#terms" ).autocomplete({ minLength: 2 });
    $( "#terms" ).autocomplete({ delay: 0 });
    $( "#terms" ).autocomplete({ select: function(event, ui) 
    { 
        var myDiv1 = document.getElementById("content");
        myDiv1.appendChild(document.createTextNode(ui.item.label));
    }

Right now all this does is when the user taps on the term in the dropdown list, the term itself which is known as ui.item.label just gets written to the content div. What I want is for the term's definition to be written. How do I set this up in JQuery where I can have the autocomplete select function simply write the definition and not the term/label?

Was it helpful?

Solution

According to This example you should be able to add all the properties you want in your source data array and be able to access them on the select event.

So your source data array could look like this:

var terms = [
    {label : "Abdomen", desc: "stomach, stomach area, belly, tummy"},
    {label : "Ability", desc: "skill"},
    {label : "Abolish", desc: "end, do away with, get rid of"}
etc...

and then in your select event definition do this:

$( "#terms" ).autocomplete({ select: function(event, ui) 
{ 
    var myDiv1 = document.getElementById("content");
    myDiv1.appendChild(document.createTextNode(ui.item.desc));
}

So the difference is that you can then use ui.item.desc instead of ui.item.label like you were using before.

OTHER TIPS

Create another separate js array with the term as the string index, like you show. Call it something else like definitions, not terms. Then when you want to append the "content" div, create a new like this

var newDefinition = definitions[ui.item.label];

And that will call the terms' definition. Then use the appendChild function like you were just doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top