Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 904
Pritam Parua Avatar asked Dec 12 '25 02:12

Pritam Parua


1 Answers

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');
});
like image 194
Rory McCrossan Avatar answered Dec 14 '25 17:12

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!