I dynamically create a button in the way I found in the Internet:
...
outPut +=
"<div class=\"col-lg-4 col-md-6 mb-4\">" +
"<div class=\"card h-100\">"+
"<img class=\"card-img-top\" src=\"http://placehold.it/700x400\" style=\"height: 50%; width:50% \" alt=\"\">"+
"<div class=\"card-body\">"+
"<h4 class=\"card-title\">"+
""+ nome +""+
"</h4>"+
"<h5>"+ preco +"</h5>"+
"<p class=\"card-text\">"+ descricao +"</p>"+
"</div>"+
"<div class=\"card-footer\" >"+
"<button type=\"button\" class=\"btn btn-success-cart\" data-id=\"" + id + "\" data-nome=\"" + nome + "\" data-descricao=\"" + descricao + "\" data-preco=\"" + preco + "\">+ Carrinho</button>"+
"</div>"+
"</div>"+
"</div>";
...
$("#divCards").html(outPut);
And Imply the method of click on each one in this way:
$(".btn-success-cart").click(function(event){
event.preventDefault();
var _id = Number( $(this).attr("data-id") );
var _nome = $(this).attr("data-nome");
var _descricao = $(this).attr("data-descricao");
var _preco = Number( $(this).attr("data-preco") );
console.log("Item add");
addItem(_id, _nome, _descricao, _preco, 1);
updateCart();
});
But nothing happens when I click the generated buttons.
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
You need to bind on a static element that exists when the code .on() is executing. Use event delegation:
$('#divCards').on('click', '.btn-success-cart', function(event){
event.preventDefault();
var _id = Number( $(this).attr("data-id") );
var _nome = $(this).attr("data-nome");
var _descricao = $(this).attr("data-descricao");
var _preco = Number( $(this).attr("data-preco") );
console.log("Item add");
addItem(_id, _nome, _descricao, _preco, 1);
updateCart();
});
I know it's a bit late to answer here but similar situation happened to me and above accepted answer worked sort of. But it fires the event multiple times because my script included to call that function which creates click event several times for different occasions. So each call would create the click event repeatedly. Then when a user click the button, the function will be called multiple times. Therefore I had to off click then on click. Just adding this answer so that anyone else has same issue with me may get help.
('#divCards').off('click', '.btn-success-cart').on('click', '.btn-success-cart', (event) => {
......
}
});
Related
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 );
I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.
I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.
I have some html in my JS and everything but the button works. The input button appears but when I click it, nothing happens.
function updateFavourite(video) {
document.getElementById("favourite").onclick = function () {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html =
"<input onclick='remove(video);' value='Remove' type='button'></input>" +
"<li class=\"saved\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
setVideoF(video);
}
}
Method to call:
function remove (video) {
alert('Favourites removed');
}
It looses its access to video variable, remove the onclick attribute and use jQuery to bind its event, and also use JavaScript Closure to keep the video variable safe:
function updateFavourite(video) {
var clickFunc = (function (video) {
return function () {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html =
"<input class='removeButton' value='Remove' type='button' />" +
"<li class=\"saved\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
$("#myfavourite .removeButton").click(function () {
remove(video);
});
};
})(video);
document.getElementById("favourite").onclick = clickFunc;
}
Your code is generating a dynamic html so click event is not registering properly. A little html updated required. Use the "removeVideo"class to your button and use the jquery to
register the click event for dynamic element.
$('body').on('click','.removeVideo', function(){
$(this).val("Clicked");
});
Insted of $('body') you can use the closest(but not dynamic element) parent.
I'm just new here. So here's where I'm stuck:
I created an html table using javascript. I have a button,which when clicked, will create set of tables with exactly the same structure but the objects(eg. button, text) inside those tables have different ID's. Now when I try to execute a click function using jQuery with a button on one of the produced tables, it won't work. How do I go around here? Thanks in advance!
Here's a sample function which creates the html table(with unique ID's) in javascript:
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
document.getElementById('HtmlPlaceHolder').innerHTML = html;
}
So, if we review the code, Sets of table with buttons(btnALERT) with unique ID's will be created if the function CreateTables is executed. In order to select the objects, I suppose I'll be using jQuery. So for example, if I bind a handler in btnALERT1(produced by CreateTables) say a click function in order to alert a simple "Hello", how will I do this? My code for this doesn't seem to work:
$(document).ready(function() {
$('#btnALERT1').click(function() {
alert("Hello");
});
});
Use .live() (for older jquery versions - < v1.7):
$('#btnALERT1').live('click', function()
{
alert("Hello");
});
Or:
$(document).delegate('#btnALERT1', 'click', function()
{
alert("Hello");
});
Use .on() (for new jquery versions - >= 1.7):
$(document).on('click', '#btnALERT1', function()
{
alert("Hello");
});
I think you may want to use the method .on():
$(document).ready(function() {
$('#btnALERT1').on('click', function() {
alert("Hello");
});
});
For more information, check the online doc: http://api.jquery.com/on/
I would use a delegate on HtmlPlaceHolder to check for click events like so:
$("#HtmlPlaceHolder").on("click", "input[type=button]", function() {
alert($(this).attr("id"));
});
Also, I would change the button id scheme to btnALERT_1, so you can extract the ID number with a .split("_") method.
You have to attach the event handlers after you create the tables, not when the document is ready (the document should be ready anyways since the user is interacting with it).
You can do this with jQuery, sure, but have a look at the native methods - jQuery might be too bloated depending on what you will do and you will learn something about the DOM.
I've added some code below which lets you add a callback and shows some things you can get back easily. It is not exactly what you asked for, but a great start to finding your way in the DOM.
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
var placeholder = document.getElementById('HtmlPlaceHolder').innerHTML = html;
placeholder.innerHTML = html;
placeholder.addEventListener('click', function (e) {
console.log(this, e);
}
}