problems in adding an element in HTML with JSON

2
var componente = {

    HTML :'<div class="alert" style="background-color:#951f2c !important;">' +
    '<input type="text" class="form-control titulo-valor" placeholder="Digite o Título do Bloco" style="background-color:#951f2c !important; color: white !important; border:none !important;"/>'+
    '</div>'
};
$(document).ready(function(){
    $(".btn").on("click",function(){
        var componenteAtual = $(this).data("componente");

        $(".resultado").html(componente.componenteAtual);    
    });    
});

I'm trying to add elements in html dynamically using JSON with multiple tags inside. It is not working, I gave an alert on componente.componenteAtual and it is returning undefined as a result. If I type componente.HTML it works ...

Below is the jsfiddle:

link

    
asked by anonymous 21.03.2016 / 16:21

1 answer

2

To deal with object properties dynamically you have to use straight parentheses, that is:

componente['nome da propriedade aqui']

When you use .html(componente.componenteAtual); this will look for a property called componenteAtual in the object, but it does not exist. What you should do is

.html(componente[componenteAtual]);

because in this way componenteAtual is converted to the value that holds ( HTML ) and in practice it stays:

.html(componente['HTML']);

jsFiddle: link

    
21.03.2016 / 16:29