user3189734
user3189734

Reputation: 665

Jquery appending values to dropdown from select

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)); 
                    });

            });

        });

    });

Upvotes: 1

Views: 1858

Answers (3)

Aneesh Mohan
Aneesh Mohan

Reputation: 1087

$.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)); 
                    });

            });

        });

    });

Upvotes: 2

Mayank
Mayank

Reputation: 1392

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..

Upvotes: 0

Pratik Joshi
Pratik Joshi

Reputation: 11693

USe $.parseJSON to fetch values ferom object

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

Upvotes: 0

Related Questions