Search code examples
javascriptjsonjson2html

Insert event handler's name to json2html's template as childern


I'm using json2Html.

  var template = {
            "tag": "tr",
            "children": [
              {
                "tag": "td",
                // "html": "<input type='radio' name='TenantID' value='${TenantID}' onclick='onTenantClick(event)'/>" // This works                
                "children": [
                {                          
                "tag": "input",
                "type": "radio",
                "name": "TenantID",
                "value": "${TenantID}",
                "onclick": "onTenantClick(event)"
                }
                ]                
              },
          ]
}; 

The "html" part works. If I add the radio element as a child (children), I get TypeError: e.data.action.call is not a function for the onclick event handler.

The doc's examples (https://json2html.com/examples/) show like this :

"onclick":function(){
                        $(this).css("visibility","hidden");

But I want to insert the function name which is in another .js file.


Solution

  • As mentioned in the json2html.com docs any on event must be a function. So if you want to call another function you'll need to wrap in like so

    var template = {
                "<>": "tr",
                "html": [
                  {
                    "<>": "td",               
                    "html": [
                    {                          
                    "tag": "input",
                    "type": "radio",
                    "name": "TenantID",
                    "value": "${TenantID}",
                    "onclick": function(e) { onTenantClick(e.event); }
                    }
                    ]                
                  },
              ]
    }; 
    

    Note that "tag" has been deprecated and replaced with "<>" and "children" deprecated and replaced with "html"