I have recently discovered an issue where I am not allowed to pass an object parameter to an onclick()
method.
I did some research and it seems to be a popular issue. I have read this:
javascript: pass an object as the argument to a onclick function inside string
and I tried to stringify the object before passing to an onclick()
but that does not seem to work.
My code:
var object_info= {
TypeID:11000,
TypeValue:5,
ValueID:12103,
ValueValue:15,
CorrectionID:11020,
CorrectionValue:0,
LabelStr:Analog_input_name[11000],
TypeStr:InputATypeStr[5],
DivId:"Test123",
};
Append_html_block(object_info);
The Append_html_block
function:
function Append_html_block(object) {
var generated_html = document.getElementById("custom_DIV");
var stringifiedObj = JSON.stringify(object);
generated_html .innerHTML += `
<table class="sensor-values-table">
<tr>
<td class="top-item" style="width:90%;">${object.LabelStr}</td>
<td>
<button style="border:none;background-color:inherit;" onclick="Expand_selection(${stringifiedObj})">
</button>
</td>
</tr>
</table>
<br>
`;
}
The logic is very simple:
I create an object which I pass to Append_html_block
function. Inside this function, I have a button. If this button is clicked, I want to perform specific actions and in order to do these actions I must know all the information about the object so I need to pass the object variable.
I didin't manage to find a clear and simple solution for passing an ojbect variable to onclick()
. Perhaps someone can suggest a neat and clean method for doing that? Thanks in advance!