J.Kirk.
J.Kirk.

Reputation: 973

Pass object to function in html in javascript?

I'm trying to pass an object on a button click, but it doesn't pass the object properly. How can I fix this?

function addEventToCart(event) {
    $("#mentorItems").append(
        `<div id="${event.id}" class="alert alert-dismissible">
        <button class="close" data-dismiss="alert" onclick=removeEvent(event)>&times;</button>
        </div>`);

The removeEvent function looks something like this:

function removeEvent(event) {
     var color = event.color;
 }

All the properties in event are undefined, so I assume something is going wrong in the passing? I've tried to follow this solution but no success either.

Upvotes: 0

Views: 2409

Answers (1)

TamirNahum
TamirNahum

Reputation: 484

The event is undefined object because you can't pass an object as plain text (you did it when you wrote removeEvent(event) I would try changing the structure:

function addEventToCart(evt) {
    var $div = $('<div id="' + evt.id + '" class="alert alert-dismissable"></div>');
    var $btn = $('<button class="close" data-dismiss="alert">&times;</button>');
    $btn.on('click', function() {
        var color = evt.color;
        alert(color);
    });
    $div.append($btn);
    $('#mentorItems').append($div);
}

Upvotes: 3

Related Questions