Yash Saraiya Yash Saraiya - 5 months ago 9
Javascript Question

Adding HTML elements in the JSON data

Following is my JSON Data validated using JSONLint:

[{
"text": "Products",
"data": {},
"children": [{
"text": "Fruit",
"data": {
"price": "",
"quantity": "",
"AddItem": "+",
"RemoveItem": "&#215"
},
"children": [{
"text": "Apple",
"data": {
"price": 0.1,
"quantity": 20,
"AddItem": "+",
"RemoveItem": "&#215"
}
}, {
"text": "Strawberry",
"data": {
"price": 0.15,
"quantity": 32,
"AddItem": "+",
"RemoveItem": "& #215"
}
}],
"state": {
"opened": false
}
}, {
"text": "Vegetables",
"data": {
"price": "",
"quantity": "",
"AddItem": "&# 43;",
"RemoveItem": "&#215"
},
"children": [{
"text": "Aubergine",
"data": {
"price": 0.5,
"quantity": 8,
"AddItem": "+",
"RemoveItem": "&#215"
}
}, {
"text": "Cauliflower",
"data": {
"price": 0.45,
"quantity": 18,
"AddItem": "+",
"RemoveItem": "&#215"
}
}, {
"text": "Potato",
"data": {
"price": 0.2,
"quantity": 38,
"AddItem": "+",
"RemoveItem": "&#215"
}
}]
}],
"state": {
"opened": false
}
}]


What I am looking for is to convert the value for the keys AddItem and RemoveItem to HTML buttons.

The above JSON will be used to render nodes in a jsTree plugin.

jsFiddle link where I will be using this json data. Basically, I want to replace my + and - sign with a button for the same

Does anyone has a work-around for this ?

Edit 1: I have read at a few places that adding HTML elements directly in your JSON data is not advisable as it can be used at a number of places in your code and each time it may have a different HTML for it. If someone has a better way to do it, that would be great.

Answer

I have never used the jsTree plugin and there is probably a better way to solve your problem, but this seems to do what i think your looking for. Just add this to the end of your code.

$(document).on('click','.jstree-table-wrapper', function() {//insted of document i would used jtrees containing div
    $.each($('.jstree-table-cell span'),function(){
        if($(this).html()=='+'){      
            $(this).html('<button class="addBtn">+</button>')
        }else if($(this).html()=='×'){      
            $(this).html('<button class="removeBtn">x</button>')
        }
    });
});

$(document).on('click','.addBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_create(id);
     $('.jstree-table-wrapper').trigger('click');
});

$(document).on('click','.removeBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_delete(id);//you might need to work on your delete function
     $('.jstree-table-wrapper').trigger('click');
});