Reputation: 5705
I have the below HTML file . I am trying to pass the item object to the javascript function : linkClickFunc so that i can process it further.
But i am unable to do it with the below syntax . Can someone please guide me as to what am i doing wrong .
<div class="container">
<h2>CodeConfig Keys</h2>
<br>
<div id="key-buttons">
</div>
</div>
<script type="text/javascript">
function linkClickFunc(item)
{
console.log(item);
}
</script>
<script>
$(document).ready(function(){
CodeConfigkeys = {"ENV": [{"NAME": "Subhayan", "Values": [{"AGE": 33, "SEX": "Male"}]}, {"NAME": "Mary", "Values": [{"AGE": 29, "SEX": "Female"}]}], "DB_PARAMS": [{"NAME": "SQL_CONNECTIONS_DB", "Values": "templates"}, {"NAME": "SQL_CONNECTIONS_COLLECTION", "Values": "dbtemplates"}]};
var html_str = "";
$.each( CodeConfigkeys, function( key, value ){
html_str = html_str + "<div class=\"btn-group dropdown\">";
html_str = html_str + "<button type=\"button\" class=\"btn btn-primary dropdown-toggle btn-primary-spacing\" data-toggle=\"dropdown\" id=\"" + "CodeConfigMenus" + "\">" + key;
html_str = html_str + "</span><span class=\"sr-only\">Toggle Dropdown</span></button>";
html_str = html_str + "<div class=\"dropdown-menu\">";
value.forEach(function(item, index, array) {
console.log(item);
console.log (typeof item);
html_str = html_str + "<li><a onclick=\"linkClickFunc($(" + "'" + item + "'" + "));\">" + item["NAME"] + "</a></li>";
});
html_str = html_str + "</div></div>";
});
console.log(html_str);
$("#key-buttons").html(html_str);
});
</script>
I have searched for possible solutions on the internet but could not hit upon the right one.
Thanks in advance.
Upvotes: 1
Views: 880
Reputation: 9476
Just change your line
html_str = html_str + "<li><a onclick=\"linkClickFunc($(" + "'" + item + "'" + "));\">" + item["NAME"] + "</a></li>";
with
html_str = html_str + "<li><a onclick='linkClickFunc("+JSON.stringify(item)+")'>" + item["NAME"] + "</a></li>";
Upvotes: 1
Reputation: 8266
Use JSON.stringify() to pass the object as a string. Of course you need to escape the double quote to be recognize as real double quotes. JSON.stringify(item)
html_str = html_str + "<li><a onclick=\"linkClickFunc($(" + "'" + JSON.stringify(item) + "'" + "));\">" + item["NAME"] + "</a></li>";
Then for the function, parse the JSON object back to string. JSON.parse(item)
function linkClickFunc(item)
{
var obj = JSON.parse(item);
console.log(item);
}
I have not tested the code but you should handle double quote for string conversion and parsing.
Upvotes: 1