dennismonsewicz
dennismonsewicz

Reputation: 25552

Select Options from JSON

I am a newb when it comes to JSON and am wanting to try to write a JSON select option autofiller, but do not know where to start.

The way my script works currently is using PHP and MySQL to fill the first set of select options with a distinct list from a DB table and then upon a user selection the next set of select options are autofilled with options that are linked to the first set. Is there anyway to do this in JSON?

Upvotes: 0

Views: 14260

Answers (2)

Tejs
Tejs

Reputation: 41256

Sure. Lets say you have some simple JSON:

{ "Options": [
    { "Text":"MyText","Value":"MyValue"},
    { "Text":"MyText2","Value":"MyValue2"}
   ]
}

Then, you evaluate that to JavaScript:

var options = eval('(' + myJson + ')'); // myJson is your data variable

Then, you simply create each option in the dom (I'll use jQuery for brevity sake)

var length = options.length;

for(var j = 0; j < length; j++)
{
    var newOption = $('<option/>');
    newOption.attr('text', options[j].Text);
    newOption.attr('value', options[j].Value); // fixed typo
    $('#mySelect').append(newOption);
}

Or something similar to this effect.

Upvotes: 6

lillq
lillq

Reputation: 15389

JSON is javascript object notation and is used for storing data.

Your web server can return JSON based on any type of request. If your web page has the JSON data you can use javascript/jquery to dynamically build the select into the dom.

Upvotes: 0

Related Questions