1

I am trying to return values within my dependant dropdown within laravel. The api/dropdown returns json, all working fine. However the values returned are not populated in my dropdown, rather they are displaying [object Object] instead.

Am I missing something?

  $(document).ready(function($){

      $('#firstselect').change(function(){

            $.get("{{ url('api/dropdown')}}", { option: $(this).val() }, 
            function(data) {
                     $.each(data, function(key, value) {   
                         $('#secondselect')
                             .append($("<option></option>")
                             .attr("value",key)
                             .text(value)); 
                    });

            });

        });

    });

3
  • When you log the values in console, what do you see? Commented Oct 10, 2014 at 8:38
  • post the JSON you get from api/dropdown Commented Oct 10, 2014 at 8:38
  • 1
    can you post what data got in data object..I think you need to go 1 level down in JSON Commented Oct 10, 2014 at 8:43

3 Answers 3

2
$.each(data,function(index,value){

//Make sure value is the string you want to attach by putting a debugger here;
//Append code;

  $('#secondselect').append($("<option></option>")
                         .attr("value",key)
                         .text(value));

});

In the code posted by you

  $(document).ready(function($){

      $('#firstselect').change(function(){

            $.get("{{ url('api/dropdown')}}", { option: $(this).val() }, 
            function(data) {
                     $.each(data, function(key, value) {   

                /**********************************************/
                //Evaluate and make sure value is string
                debugger;
                console.log(value);
               /*************************************************/

                   $('#secondselect').append($("<option></option>")
                             .attr("value",key)
                             .text(value)); 
                    });

            });

        });

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

Comments

0

USe $.parseJSON to fetch values ferom object

 function(data) {
 data =  $.parseJSON(data);
 ...

Comments

0

Try the FIDDLE

html

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

jquery

$(function () {
    var $val = "Random";
         $('select').append('<option value="'+$val+'">'+$val+'</option>');

        });

hope it helps..

Comments

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.