Pritam Parua
Pritam Parua

Reputation: 692

Jquery dynamically create element | onclick pass string parameter

I am creating HTML dynamically but I am getting a syntax error. If I change href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')" than I am getting error saying 'video not defined'.

html +='<li><a href="javascript:startChat('+user_id+','video')"><i class="uk-icon-video-camera uk-icon-large"></i></a></li>';

function startChat(user_id, type){
    console.log(type);
}

Upvotes: 3

Views: 1818

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

As you can see from the syntax highlighting in your question, you're not escaping the quotes in the string correctly. Try this:

html += '<li><a href="javascript:startChat(' + user_id + ', \'video\')"><i class="uk-icon-video-camera uk-icon-large"></i></a></li>';

function startChat(user_id, type){
    console.log(type);
}

Also note that it would be much better practice to use a delegated event handler to achieve this instead of outdated inline event attributes. Try this:

html += '<li><a href="#" data-userid="' + user_id + '"><i class="uk-icon-video-camera uk-icon-large"></i></a></li>';

$('ul').on('click', 'li', function(e) {
    startChat($(this).data('userid'), 'video');
});

Upvotes: 5

Related Questions