Reputation: 126
I am creating an HTML element in a variable as a string and calling a function on its click. The issue is that when I am trying to pass an object to the function as a parameter, it is not being sent properly. When the function is called, I am simply consoling the object passed and it is logging [object Object], so its not accessible as an object. What am i doing wrong?
fnCreateElement: function(obj) {
let mainObj = obj
console.log('JSON received ----', obj)
let el = '<span class="field-actions d-block">' +
'<i id="edit" class="fa fa-pencil pr-3 pointer" onclick="openModal(\'' + obj + '\')" aria-hidden="true"></i>' +
'<i class="fa fa-times pointer" aria-hidden="true" onclick="removeElement(\'' + obj.id + '\')"></i>' +
'</span>';
The first console is printing the object properly in the fnCreateElement function but when the openModal function is called, it is causing the issue.
openModal = (obj) =>{
console.log(obj) // output ---> [object Object]
}
Upvotes: 1
Views: 160
Reputation: 76
The problem is that you're passing your JSON object to the openModal
function as a string by quoting it. Removing the quotes should do the trick
onclick="openModal(' + obj + ')"
Upvotes: 0
Reputation: 337560
You could potentially parse the object to JSON before concatenating it, but this is creating more problems than it solves for two reasons. Firstly you'll have to work around the mismatched quotes in the resulting JSON by escaping them, and secondly you'll then need to parse the JSON again in the function you call.
A much better approach is to apply the object to a data
attribute on a common parent element and then read it back out via delegated event handlers.
Also note that you are creating id
attributes in the HTML you dynamically create. This can lead to duplicates if the function is called multiple times. To avoid this use class
attributes on the elements instead.
With all that said, try this:
let obj = {
id: 'abc123',
foo: 'bar'
}
// in the logic which creates the elements:
let $newContent = $('<span class="field-actions d-block">' +
'<i class="fa fa-pencil pr-3 pointer edit" aria-hidden="true">Edit</i> ' +
'<i class="fa fa-times pointer remove" aria-hidden="true">Delete</i></span>').appendTo('#container');
$newContent.filter('.field-actions').data('obj', obj);
// delegated event handlers somewhere else in your logic:
$('#container').on('click', '.edit', function() {
console.log($(this).closest('.field-actions').data('obj'));
}).on('click', '.remove', function() {
console.log($(this).closest('.field-actions').data('obj').id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
Upvotes: 0
Reputation: 3434
This is the expected behavior. If you want to display the object as a string in the console, then use stringify().
Upvotes: 1