2

like the title says, I am trying to create a drop down menu using jQuery, JSON and AJAX, although I am familiar with the theory I have yet to put it into practice, any advice, demo code snippets or tutorials would be appreciated, since I would like to get off to the best possible start!

Thanx in advance!

1
  • Your question is too broad and has many unknowns. What server technology are you using? Commented Aug 25, 2010 at 9:34

2 Answers 2

5

You need to do $.getJSON call to fetch json from server on document.load or on some other event http://api.jquery.com/jQuery.getJSON/ . After that you have to loop through the data and append it to your select box. see that http://www.jsfiddle.net/Dyc9Y/1/

<select id="fillME"></select>
<button id="startFilling" value="">Start ajax</button>
$(function(){
 var json = {
                 "0":  {"title":"localjsonOPtion1", "value":"b"},
                 "1":  {"title":"localjsonOPtion2", "value":"a"}
            };

  $("#startFilling").click(function(){

    $.getJSON("http://localdev.myvouchercodes.co.uk/local/default/search/jsonresponse", function(data){
         $("#fillME").html("");
        for(key in data)
            $("#fillME").append("<option value='"+json [key].value+"'>"+json[key].title+"</option>");
        for(key in json)
            $("#fillME").append("<option value='"+json [key].value+"'>"+json[key].title+"</option>");
   });    
 });
});

offcourse above example depends on json with following format.

{ 
   "0":  {"title":"option1", "value":"1"},
   "1":  {"title":"option2", "value":"2"}
}

EDITED: You also need to be familiar with select box change event http://api.jquery.com/change/ and :selected selector that will allow you to fetch selected option from the selectbox http://api.jquery.com/selected-selector/ like $("select option:selected")

Sign up to request clarification or add additional context in comments.

3 Comments

also you can view this tutorial hungred.com/how-to/…
Awesome, thanx for all the info! Ill be going through it in a bit! Will report back with questions or a success story!
Sorry for the belated reply, but I am going through the code now, and I have posted a question here stackoverflow.com/questions/3607026/…
5

This should do the trick:

$.getJSON("test.php", function(data){
  $.each(data, function(index, text) {
    $('#mySelect').append(
        $('<option></option>').val(index).html(text)
    );
  });
});

note: test.php should return an json encoded array

1 Comment

Thanx so much, I will try it out in a bit and report back to you guys!

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.