problems adding an element to HTML with JSON

Asked

Viewed 53 times

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 dynamically add html elements using JSON with multiple tags inside. It’s not working, I gave an Alert on componente.componenteAtual and he’s returning undefined as a result. If I write componente.HTML works...

Below is the jsfiddle:

https://jsfiddle.net/vxq92vzw/

1 answer

2


To adjust the properties of objects in a dynamic way you have to use straight parentheses, i.e.:

componente['nome da propriedade aqui']

When you use .html(componente.componenteAtual); This will look for a property called componenteAtual in the object, but it doesn’t exist. What you should do is

.html(componente[componenteAtual]);

for in that way componenteAtual is converted into the value it holds (HTML) and in practice:

.html(componente['HTML']);

jsFiddle: https://jsfiddle.net/Lr033bna/

Browser other questions tagged

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