Error while passing parameter to javascript function dynamically - javascript

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

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' );

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>");

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(.......)\"

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(...);
});

Related

<i class="fa fa-trash"> is not working in <span></span>

I was going through the solutions of Uncaught SyntaxError: missing ) after argument list, and tried every other way to sort it out but I am still getting this error with this code
$("input").on("keypress",function(event){
if(event.which === 13)
{
var ToDotext=($(this).val());
$("ul").append("<li><span><i class="fa fa-trash"></span> " + ToDotext + "</li>");
$(this).val("");
}
}
);
whenever I put <i class="fa fa-trash" in <span></span> I am getting this error, without <i class="fa fa-trash"> things are working fine.
Change the appending line to this.
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + ToDotext + "</li>");
Changes:
fa fa-trash is in single quotes as you are using double quotes outside.
close the i tag
Suggestions:
Instead of using <i> inside <span>, apply the class on span or remove span altogether and keep i tag.
Use jQuery element creation methods. like this.
$('ul li ').html($('<i>', {class: 'fa fa-trash'}));
Use this code
$("input").on("keypress",function(event){
if(event.which === 13)
{
var ToDotext=($(this).val());
$("ul").append("<li><span><i class='fa fa-trash'></i></span>"+ ToDotext + "</li>");
$(this).val("");
}
});
I found the error in your script.
$("ul").append("<li><span><i class="fa fa-trash"></span>"+ToDotext+"</li>");
If you add component, with this code, the actual components are added as follows.
<li><span><i class=fa fa-trash></span>ToDoText</li>
As you see above, the class names of the <i> tag must be quoted with " or ' but it is not like that.
It is because you used the same quotes adding the components.
If you change "fa fa-trash" -> 'fa fa-trash', the problem will be solved.
You can't have double quotations inside double quotations, simple example:
open your console:
var newElem = "<h1 class="rock">Hello There !!</h1>";
newElem // Uncaught SyntaxError: Unexpected identifier
You will have to enclose you class and other html attributes inside a single quotations, like so:
var newElem = "<h1 class='rock'>Hello There !!</h1>";
The below line:
$("ul").append("<li><span><i class='fa fa-trash'></span> " + ToDotext + "</li>");
Would have to change to:
$("ul").append("<li><span><i class="fa fa-trash"></span> " + ToDotext + "</li>");
Additional ::- if you writing long concatenations you probably want to SPLIT IT UP INTO ADDITIONAL LINK

Bind function only works on last element

I am creating an application to store my homeworks, whenever I touch the li of the homework, the information of this homework yould be displayed from a sqlite database. My problem is that when I add each li from javascript, I bind a function so that each time I touch the item it will return its uid. But whenever I add a new hw, the other ones wont return their uid.
Some of my code:
function newFormSuccess(tx, results){
var lista = $("#lHw");
var obj = $(
'<li><a id="' + results.id + '" href="#detalle" data-uid=' + results.id +
' class="ui-btn ui-btn-icon-right ui-icon-carat-r" data-transition="pop" data-direction="reverse">' +
'<h2>' + results.title + '</h2>' +
'<p>' + results.desc + '</p><p>' + results.date + '</p>' +
'<p class="ui-li-aside">Type</p></a>' +
'</li>'
);
obj.find('#' + results.id).bind('click', function (e) {
$.id = $(this).data('uid');
});
lista.append(obj).listview('refresh');
$.mobile.changePage("#home");
}
Any suggestions? Why is this happening?
I fixed the problem by changing the bind to .on, and using it ona a device ready function, I think this is what the Delegate comments where all about.
$("#lHw").on("click", "li a", function(e){
$.id= $(this).data('uid');
});

Escaping quotes coming from JSON

I get some data from JSON and put it as a custom attribut data-info into an a-tag. When clicking on this link, the information should appear:
$("#div").append("<a href='#' data-info='" + value.info + "'>" + value.name "</a>");
Unfortunately, JSON may contain some quotes that break my code:
Some text
How can I escape all quotes coming from JSON?
Do it properly.
var a = document.createElement('a');
a.setAttribute("href","#");
a.setAttribute("data-info",value.info);
a.appendChild(document.createTextNode(value.name));
$("#div").append(a);
Done ;)
With jQuery you can use attr
var $link = $('<a href="#" />').text(value.name).attr('data-info', value.info);
$("#div").append($link);
Here is what you wanted:
$("#div").append("<a href='#' data-info='" + value.info.replace("'", "\'") + "'>" + value.name "</a>");
But you should do it like #Niet the Dark Absol's answer 😉

Trying to escape quotes in a href tag

I have the following line of code,
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
I essentially want the "data.response.results[i].webUrl" to replace the url string, but I'm not quite sure how to escape the quotes properly.
You can escape quotes by replacing them with \"
or just use single quotes - '
So "<div><a href="url">" becomes
"<div><a href=\"url\">" or "<div><a href='url'>"
a single quote ' and a string concatenator +
$("#busdata").append("<div><a href='"+ data.response.results[i].webUrl +"'>" + data.response.results[i].webUrl + "</a></div>");
Your syntax is wrong. You need to escape quotes. Change your <a href="url"> to <a href=\"url\"> like this:
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
Or if you feel that's a bit tough, you can exchange the quotes, ' for ":
$("#busdata").append('<div>' + data.response.results[i].webUrl + "</div>");
Else, if you are trying to add the URL from the response:
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
if url is a variable
$("#busdata").append("<div><a href='" + url +"'>" + data.response.results[i].webUrl + "</a></div>");
and if you want to write by yourself
$("#busdata").append("<div><a href='url'>" + data.response.results[i].webUrl + "</a></div>");
You can store it in variable instead :
var url = data.response.results[i].webUrl;
$("#busdata").append("<div>" + url + "</div>");
Hope this helps.
Simply do it following my example:
var a = $('<a />', {
href: 'url here',
text: 'text here'
}); $('body').append(a);
You could do this :
$("#busdata").append("<div><a href='"+data.response.results[i].webUrl +"'>" + data.response.results[i].webUrl + "</a></div>");
Since you are using double quotes for the string to append, you can use single quotes around the variable in the href attribute and then add that variable.
This is most easily achieved by not building HTML by smashing strings together in the first place.
$("#busdata").append(
$("<div />").append(
$("<a />").attr("href", data.response.results[i].webUrl)
)
);
Escaping quotes is not necessary
$("#busdata")
.append("<div><a href="
+ data.response.results[i].webUrl
+ ">"
+ data.response.results[i].webUrl
+ "</a></div>"
);

Javascript function call doesn't work from a link

I try to call a custom made function from a link but somehow it doesn't work. Alert doesn't pop up. Help appreciated! This is my code:
$.each(data.Tables, function(i, data){
link = '<a href="#" onclick=test()>' + data.tableName + '</a>';
tr.append("<td>" + link + "</td>");
tr.append("<td>" + data.rowCount + "</td>");
$("#tablesTable").append(tr);
});
This is my function:
function test (){
alert("Doesn't work");
}
If I change the link row to this, alert comes after clicking the link.
link = '<a href="#" onclick=alert()>' + data.tableName + '</a>';
JavaScript has no place in HTML attributes. jQuery can actually bind event handlers to elements even if they are not in the DOM, so I'd suggest you do something like this:
$.each(data.Tables, function(i, data){
var $link = $('<a></a>', { // Create a new jQuery object
href: '#',
html: data.tableName
}).click(function(){
// Your code here...
alert("Doesn't work");
});
// We can't use '+' since $link is no longer a string
tr.append($link.wrap('<td></td>').parent());
tr.append("<td>" + data.rowCount + "</td>");
$("#tablesTable").append(tr);
});
This uses jQuery to create the <a> tag, then uses .click() to bind the event.
Change this
link = '<a href="#" onclick=test()>' + data.tableName + '</a>';
to this
link = '' + data.tableName + '';

Categories