Reputation: 2790
I am creating list dynamically. When user click on that li element setCollege method will be called.
Code to generate li
is:
$('#dropDown ul').append("
<li onclick=setCollege("+ data[i].id +",'"+ data[i].college_name +"')><i class='fa fa-university'></i>" + data[i].college_name + "</li>");
but javascript dynamically add "
after space in college name like
<li onclick="setCollege(3,'Nirma" university')"> <i class="fa fa-university"></i>Nirma University</li>
due to "
, it produces error while calling js function
Upvotes: 0
Views: 345
Reputation: 15629
Because you don't add the surrounding "
to your onclick attribute:
$('#dropDown ul').append("
<li onclick=\"setCollege("+ data[i].id +",'"+ data[i].college_name +"')\"><i class='fa fa-university'></i>" + data[i].college_name + "</li>");
but why don't you use jQuery to attach the event to the list items? This would be the better solution:
$('#dropDown').on('click', 'li', function() {
setCollege(...);
});
Upvotes: 0
Reputation: 998
onclick is a html attribute, thus it needs to be put in quotes itself.
Try this instead:
var tpl = '<li onclick="setCollege(' + data[i].id + ', ' + data[i].college_name + ' );"><i class="fa fa-university"></i>' + data[i].college_name + '</li>';
$('#dropDown ul').append( tpl );
Pay attention to single vs. double quote usage.
But since your question is flagged as jquery, I'd suggest:
var listItem = $( '<li></li>' ).text( data[i].college_name );
$( '<i class="fa fa-university"></i>' ).prependTo( listItem );
listItem.on( 'click', function() {
setCollege( data[i].id, data[i].college_name);
});
listItem.appendTo( '#dropDown ul' );
Upvotes: 1
Reputation: 2819
Your concatenation starts with double quotes("
). So you need to follow till the end of the statement.
Try this,
"'+ data[i].college_name +'"
instead of
'"+ data[i].college_name +"'
Also add double quotes(" "
) surround by the onclick event, and escape them,
onclick=\"setcollege(.......)\"
Upvotes: 0
Reputation: 10141
Try using like:
$('#dropDown ul').append("
<li onclick=setCollege("+ data[i].id +",""+ data[i].college_name +"")><i class='fa fa-university'></i>" + data[i].college_name + "</li>");
Upvotes: 0