1

hi I want a function like this! https://i.sstatic.net/p61fq.png

when I select the first "select tag"

the secoud "select tag" show undefined

but in this picture the CONSOLE area is exactly show what I want.

My problem is...how to show the data in second "select tag"?

I think it's something wrong in my javascript.

$.ajax({
    type: "POST",
      url: "dropdownServlet",
      data: dataString,
      dataType: "json",
      success: function( data, textStatus, jqXHR) {
          $("#dropdown2").html("");
            $.each(data, function(){
                $.each(this,function(){
                    $("#dropdown2").append("<option>"+data.CiytName+"</option>");   
                });
            });            
     },

and this's my json data

[{"CityId":"4","CityName":"Vancouver"},{"CityId":"5","CityName":"Toronto"}]
2
  • For starters, your code is incorrectly looking for data.CiytName... Commented Jun 10, 2013 at 2:46
  • 1
    Why are you doing 2 foreach loops? That appears wrong, also data.CiytName should be data.CityName. Commented Jun 10, 2013 at 2:46

1 Answer 1

2

All you need to do is this:

    $.each(data, function(_, ob){
        $("#dropdown2").append("<option>"+ob.CityName+"</option>");   

   });    
  1. Since your data is already [{"CityId":"4","CityName":"Vancouver"},{"CityId":"5","CityName":"Toronto"}] you just need to use one level of $.each iteration and data.CiytName has 2 issues,
  2. data is the original object (Not the object of this iteration)
  3. CiytName has a typo.

Just my suggestion not to append in the $.each loop iteration to reduce the number of DOM operations especially when you have huge data in your json to be appended as option.

      var select = $('<select/>'); //Create a temp element.
        $.each(data, function(){
                select.append("<option>"+ob.CityName+"</option>");   //append to the temp element 
         });       

        $("#dropdown2").html(select.html());  //finally fill in the dropdown with your latest options.

Refer $.each

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

3 Comments

thanks lot! Do you know about this $.each(data,function(_,ob) tutorial resource can I learn?
@劉承緯 Updated my answer with reference link. Did this resolve your issue?
+1 from me as well. Explained it perfectly.

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.