How to pick up space values in JSON

Asked

Viewed 864 times

1

Hello. I have a problem with the 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:

Select

Console

Note that the <option value="Alfa" romeo></option> is being filled out incorrectly.

Something wrong with the code? Any suggestions ?

Hugs!

  • How am I supposed to show up? Test for example: var option = '<option value="'+make.join(' ')+'">'+make.join(' ')+'</option>'; looks like what you’re looking for?

  • 1

    good practice is when the key ( can be variable ) has more than one word use lowercase and together by a hyphen, thus prevents these problems , if you can change this part would avoid these problems.

  • @Sergio when I try to use . Join(): Uncaught Typeerror: make.Join is not a Function

  • Solution: var $option = $('<option />')&#xA; .prop('value', make)&#xA; .prop('text', make);&#xA; $("#marcas_list").append($option);

2 answers

1

Separation has no problem in 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>
<select id="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);
});

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>
<select id="options"></select>

  • That’s how it worked too! The solution I used was this: https://jsfiddle.net/xqgaevzo/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.