How to get values with space in JSON

1

Hello. I'm having a problem with a popular select with JSON. When the value has 2 or more words the 'value' of my option is not filled correctly. Example:

{
"Marcas": {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },

    "Alfa Romeo": {
        "Modelos": ["145", "147", "155"]
    }
}


$.getJSON('models.json', function(data) {
    $.each( data, function( key, val ) {
        $.each(val, function(make, value){
            console.log(make, value)
            var option = '<option value='+make+'>'+make+'</option>';
            $(option).appendTo("#marcas_list");
        });
    });
});

Results:

Notethat<optionvalue="Alfa" romeo></option> is being filled incorrectly.

Anything wrong with the code? Any suggestions?

Hugs!

    
asked by anonymous 04.10.2016 / 00:00

2 answers

1

Separation has no problem loading look at the example!

var items = {
"Marcas": {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },
    "Alfa Romeo": {
        "Modelos": ["145", "147", "155"]
    }
}};

var opt = "";
$.each(items.Marcas, function( key, val ) 
{
	opt = opt + '<option value="' + key + '">' + key + '</option>';
});
$("#marcas_list").html(opt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="marcas_list">
</select>

In your code:

$.getJSON('models.json', function(data) {
    var opt = "";
    $.each( data.Marcas, function( key, val ) {
        opt = opt + '<option value="' + key + '">' + key + '</option>';
    });
    $("#marcas_list").html(opt);
});
    
04.10.2016 / 00:18
1

You can do this without problem through object, using document.createElement .

var marcas = {
"Marcas" : {
    "Acura": {
        "Modelos": ["Integra", "Legend", "NSX"]
    },
    "Alfa Romeo" : {
        "Modelos": ["145", "147", "155"]
    }
}}
  
$.each(marcas['Marcas'], function(key, value){
  var option = document.createElement('option');
  option.textContent = key;
  option.value = key;
  $('#options').append(option);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><selectid="options"></select>
    
04.10.2016 / 01:04