Javascript function call doesn't work from a link - javascript

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

Related

jquery call function from dynamic div

I am using jquery. I have a div that is populated by jquery. Inside div, there is a list of items under row tag. And, Inside, the dynamic div section, I also have a anchor tag. On clicking on that anchor tag, I want to call the ajax function. Is it even possible?
var content='';
$.each(products, function(key, value) {
content += '<div class="row">' +
'<img src="' + value.image + '" class="img img-responsive" style="height: 65px;"/>' +
'<h3>' + value.name + '</h3>' +
'<p>' + value.category + '</p>' +
'</div>' +
'Delete' +
'<hr>';
});
modal.find('.modal_product_list').html(content);
When the anchor tag is clicked, I want to call ajax function. Here is my ajax sample:
$('.delete_product_from_space').on('click', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});
The on click event is never fired. Is it possible to call like this? Or I am approaching in a wrong way?
You may try to add the event on modal, as the dynamically generated elements would not be available at the time of code execution. Try the below code,
$('.modal_product_list').on('click', '.delete_product_from_space', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});

onclick function in loop, executes without clicking

Im fetching data from a blizzard api(working fine) and i have a jquery $each loop to retrieve the data which i then append in a ul. i want to add a button within every time the loop gives out data to an object. the problem is that when i use onclick='"+myfunction(param)+"' inside the loop, it will execute the function before i have pressed the button the onclick is attached to. when i check the browser it says onclick="undefined". here is the code:
let tid;
function reply_click(clicked_id){
console.log(clicked_id);
}
$('#searchnow').bind('click',
function (){
function kaldapiclass(){
// console.log("card");
var classSelect=$('#thisclass').val();
$.getJSON('https://us.api.blizzard.com/hearthstone/cards?
locale=en_US&access_token=hidden&class='+classSelect, function(data) {
$('#kortliste').empty();
$.each( data.cards, function(i, card) {
$()
$('#kortliste').append("<li id='" + card.id + "'><img src='" + card.image + "'><p>"+
card.name +"</p><button onclick='"+reply_click(card.id)+"'>HERE</button></li>");
});
});
};
clearTimeout(tid);
tid=setTimeout(kaldapiclass, 500);
});
ty for your time
-Morten
The code you entered will actually execute the function. So, instead of:
"<button onclick='"+reply_click(card.id)+"'>HERE</button>"
you should just define the element the way you would place it in dom:
"<button onclick='reply_click("+card.id+")'>HERE</button>"
Only the card.id should be dynamic.
I would also suggest to append html only once, this way:
var toAppend = '';
$.each( data.cards, function(i, card) {
toAppend += "<li id='" + card.id + "'><img src='" + card.image + "'><p>" + card.name + "</p><button onclick='reply_click(" + card.id + ")'>HERE</button></li>";
});
$('#kortliste').html( toAppend );

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

Jquery addEventListener in Chrome with parameters

A feature was developed in an application by clicking a hyperlink in a table, open a div below with a table, filtering contents, depending on the link.
The link was created dynamically in one jQuery function and had the following attributes:
$("#pending div#list").bind("data_loaded", function (event, records) {
var tableBody = $("tbody", $(this));
for (var index = 0; index < records.length; index++) {
var rowHtml = '<tr id="' + rowid + '"><input type="hidden" name="' + rowid + '" id="' + rowid + '" value="1"/>' +
'<td><a class="populate" id="' + rowid + '" onclick="javascript:clickHandler(' + rowid + ');">' + docid + '</a></td>' +
'</tr>';
tableBody.append($(rowHtml));
}
});
In Mozilla Firefox, it works perfectly fine. However in Chrome I cannot call the clickHandler function.
From the information I find on Google, say Inline JavaScript will not be executed.
You can check here: https://developer.chrome.com/extensions/contentSecurityPolicy
But now comes my difficulty.
I changed my hyperlink to:
'<td><a class="populate" id="' + rowid + '" onclick="clickHandler(' + rowid + ');">' + docid + '</a></td>' +
And I created this jQuery:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById([parameter]).addEventListener('click', function () { clickHandler([parameter]); },false);
});
Can anyone explain how I can pass the parameter rowid for jQuery?
Thanks.
Regards.
Your snippets imply you're using raw DOM manipulation in Javascript rather than JQuery (which is good! it's definitely faster) but since you mention JQuery, that's what I'll be suggesting.
Instead of your addEventListener call above, try
$('div#list').on('click', 'a.populate', function() {
clickHandler($(this).attr('id'));
});
And then remove the 'onclick' attribute in the declarations of the anchor tags too.
This will add an event listener to all anchor tages with a class of 'populate' which will call clickHandler passing a string parameter consisting of that anchor tag's 'id'.

Error while passing parameter to javascript function dynamically

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

Categories