Robert Hanson Robert Hanson - 7 months ago 9
Javascript Question

jQuery failed to append JSON data as select option

I have this HTML structure :

<div class="row">
<div class="col-sm-6 p-l-0">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="kurir">
<option select="selected"></option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
</select>
</div>
</div>
</div>


and I also have this javascript :

$(".kurir").change(function() {

var json_url = "some url here";

$.getJSON( json_url, function( data ) {
var tarif_items = [];
$.each( data, function( key, val ) {
tarif_items.push( "<option value='" + key + "'>" + val + "</option>" );
});

$(this).parent().parent().next().find('.tarif').append(tarif_items);
});
});


I can get
key
and
val
perfectly from JSON data, but why I still get empty option in
.tarif
? why jquery failed to append
tarif_items
? thank you so much.

Answer

It fails because you are trying to append an array instead of an HTML string.

To fix this:

var $this = $(this);

$.getJSON( json_url, function( data ) {
    var tarif_items = "";
    $.each( data, function( key, val ) {
        tarif_items += "<option value='" + key + "'>" + val + "</option>";
    });

    $this.parent().parent().next().find('.tarif').append(tarif_items);
});

I also suggest you to add an id attribute to that select like

<select id="tarif" disabled class="tarif">
  <option select="selected"></option>
</select>

And change the code like this

// $this.parent().parent().next().find('.tarif').append(tarif_items);
$('#tarif').append(tarif_items);

and finally, as a final improvement. I suggest you to do make a reset to avoid further issues:

HTML:

<select id="tarif" disabled class="tarif">
  <!-- no default option -->
</select>

JS:

$.getJSON( json_url, function( data ) {
    $('#tarif').html(''); // this resets the select content each time we receive the json
    var tarif_items = "<option select="selected"></option>"; // here it goes
    $.each( data, function( key, val ) {
        tarif_items += "<option value='" + key + "'>" + val + "</option>";
    });

    $('#tarif').append(tarif_items);
});

This way you can also call the function multiple time and regenerate the select.