How to call jQuery click event from innerHTML? [duplicate] - javascript

This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 2 years ago.
In my javascript on load in my index.html, I am getting the data from my backend (Flask app) and putting in a javascript variable. The reason why i am doing this is that while I can directly inject from flask end using {% data %} and do a for loop, I want to do filtering on my data dynamically. For this instead of me fetching from my server always, this is why i load it into a javascript object.
Index.html
<script type="text/javascript">
window.onload = function() {
var productdata = JSON.parse('{{ data | tojson | safe}}');
console.log(productdata)
var output = "";
for (var i in productdata) {
output += "<div class='item' data-product style='float: left; width: 200px;'>"
+ "<article class='product'>"
+ "<a href='/getproduct?priceid=" +productdata[i].priceid+ "'data-url'>"
+ "<img src="+ productdata[i].images+" class='img-fluid' data-img></a>"
+ "<div class='price-group'>"
+ "<div class='price'><span class='currency' data-product-currency>$</span> <span data-product-price>"+productdata[i].price+"</span></div>"
+ "</div>"
+ "<h3><a>"+productdata[i].name+"</a></h3>"
+ "<div class='btngroup'>"
+ "<a type='button' onclick=specialcart() class='add-to-cart btn btn-sm btn-secondary' title='Add to Cart' data-id=" + productdata[i].id + " data-name="+productdata[i].name+" data-price="+productdata[i].price+"></i> Add to cart</a>"
+ "</div>"
+ "</article>"
+ "</div>"
}
document.getElementById('products').innerHTML=output;
}
</script>
I have a jquery function
$('.add-to-cart').click(function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});
By right, when i call this jquery event, my data will be added into a js array. I have tested it using a static button and it works. However, i notice my button in my js code above in the index.html which is calling my jquery event is not working (nothing is happening).
So my question is how do we call jquery event within my document.getElementById('products').innerHTML=output?

I think it's because .click won't work on dynamically added elements.
Try using .on('click',...) instead.
$('.add-to-cart').on('click', function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});

I think you have to target your click listener through the document like so
$(document).on('click', '.add-to-cart', function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});

Related

How to get data attribute value using jquery

I am working on jquery with php,Right now i have button inside loop and i want to pass "data attribute" and want to get value,Right now i am getting "undefined",So how can i do this ?
Here is my current code
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap();'><img src='assets/viewmap.png'></a>"."</td>";
<script>
function viewmap()
{
var ids = $(this).attr('data-id');
alert('id is ' + ids);
}
</script>
change your onclick to this
onclick='viewmap(this)'
and get data with jquery like this
function viewmap(elm){
var id = $(elm).data('id');
alert('id is ' + id);
}
Pass this in onclick function and get in viewmap function and access
You can try below code ..
PHP
<?php
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'><img src='assets/viewmap.png'></a>"."</td>";
?>
Script
<script>
function viewmap(m)
{
var ids = m.attr('data-id');
alert('id is ' + ids);
}
</script>
The problem is that you are using this inside your function viewmap but you are not sending it as a parameter from the HTML code, Change your onclick by: onclick='viewmap(this); than change the js function like bellow:
function viewmap(e)
{
var ids = $(e).attr('data-id');
alert('id is ' + ids);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='1254' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'>
click here
</a>
Remove onclick attribute and change the viemap() function like this
$(".map-pop").click(function(e) {
e.preventDefault();
let ids = $(this).data('id');
alert(`id is ${ids}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal'><img src='assets/viewmap.png'></a>
`

How can I get attributes from dynamically created buttons?

So, I am building some sort of e-commerce website and I needed to import a bunch of products from a mysql database, using nodejs and ajax.
I've been able to get that so far, aswell as creating certain buttons below each product that will lead to a /product page where additional information will be displayed of that exact product.
Since those buttons were not dynamic, I had the need to add an attribute, which will contain the products ID, which I will then use to send a POST request to the server so I can get the information about that specific product.
And although I was able to add the attribute to the buttons themselves, I have no idea how to get their value.
This is how I added my attributes to the buttons.
$(function () {
$.ajax({
type: 'POST',
url: '/getPacotes',
success: function (data) {
for (var i = 0; i < data.length; i++) {
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
var precoPacote = data[i].Preco_Pacote;
var fornecedorPacote = data[i].Fornecedor_Pacote;
var foto = "https://webitcloud.net/PW/1617/RMR/Views/images/Pacotes/" + data[i].Foto;
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<img src=" + foto + " alt='Mountain View' style='width:150px;height:150px;'><br><br><input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
$("#pacotes").append(pacoteSet1 + "<h1>" + nomePacote + "</h1>" + "<h2>" + fornecedorPacote + "</h2>" + "<h3>" + precoPacote + "euros/mes </h3>" + pacoteSet2 + pacoteSet3);
$(document).find("#btnPac" + i).attr({
"idPacote": idPacote
});
}
}
});
});
And this is how I was trying to get their attributes
$("button").each(function () {
console.log(this.idPacote);
$.post("http://localhost:3000/pacote?id=" + this.idPacote);
});
But it doesn't seem to work
idPacote returns undefined and I have no idea why, because I simply give the buttons an "id" and replace the idPacote with the "id" itself, it will return the buttons ID
Sorry if the question sounds dumb. I am not very experienced in these matters.
When you are using jQuery I would suggest you to use the HTML5 data attribute in order to set a specified attribute to a HTML element:
<button data-id="1"></button>
You can set and access it using jQuery:
$('button').data('id', value); //set data-id
$('button').data('id'); //Read data-id
Furthermore change
<input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>
to
<button name='comprar'>Comprar Pacote</button>
in order to get elements from $('button')

how do i capture which number <div> got clicked on inside my container <div> and store it in a variable

edit: my code is all held inside a $(document).ready(function() {} because of this, and because my html code is generated inside my javascript file on the fly, i am experiencing issues using .click() when applying the answer that was given to use
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
original:
i have 20 div elements on a page with a class of .movies_cell that are all generated from an ajax file. All of the div's are created within container div called #movies.
any of the .movies_cell div's can be clicked to bring up a modal box, because i am going to place information from my json file in that modal depending on what gets clicked i need to know which div got clicked, for instance, if it was the 5th div i want to know that the 5th div was clicked and then store that number in a variable, if it was the 2nd, or 3rd i want that number to be stored in a variable and then clear when another .movies_cell div gets clicked.
how would i write a javascript or jquery script to accomplish this? :(
thanks!
$('#myMovies').click(function () {
$.getJSON('data/movies.json', function (allData) {
$.each(allData, function (i, field) {
$('#movies').append(function () {
var movies = '<div class="movies_cell">';
movies += '<div class="movies_image">';
movies += '<img src="img/movies/' + (field.image) + '" alt="' + (field.name) + ' Poster" style="width: 100%; height: 100%">';
movies += '</div>';
movies += '<div class="movies_detail">';
movies += '<h1>' + (field.name) + '</h1>';
movies += '<img src="img/rating/' + (field.myRating) + '.png" alt="movie rating" style="margin: auto;">';
movies += '</div>';
movies += '</div>';
counter++;
console.log(counter);
return movies;
});
});
});
});
Use event delegation.(https://api.jquery.com/on#direct-and-delegated-events) At the top
$('#movies').on( "click", ".movies_cell > div", function() {
var tmp = $(".movies_cell > div").index(this);
console.log(tmp);
});
then
$('#myMovies').click(function () {
//rest of code
Can you use .index() ? It is a zero-based index of the collection of items with, for example, class="movies_cell"
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
jsFiddle Demo

button created via jquery not triggering a .click event [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Click event for elements added to DOM dynamically
(2 answers)
Closed 9 years ago.
I have the following jquery code to create a button for each row in a table:
$("#add_to_rule").click(function(){
var contact_type=$("#contact_types option:selected").val();
var email_address = $('#email_address').val();
var call_order = $('#call_order').val();
var htmlstring = '<tr>'
htmlstring = htmlstring + '<td><input type="button" value="Remove" class="removeruleset"/></td>'
htmlstring = htmlstring + '<td>' + contact_type + '</td>'
htmlstring = htmlstring + '<td>' + email_address + '</td>'
htmlstring = htmlstring + '<td>' + call_order + '</td>'
htmlstring = htmlstring + '</tr>'
$('#rule_summary tr:last').after(htmlstring);
});
Then, I've got some more jquery to handle the .click event for the remove button:
$(".removeruleset").click(function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
The code to add a row to my table, along with the remove button works. But when I click on one of the remove buttons, it doesn't trigger the click event.
As a test, I created a button like so, outside of jquery:
<input type="button" class="removeruleset" value="push me">
and it triggers the click event no problem.
Can you tell me where I'm going wrong?
Thank you.
EDIT 1
I've tried changing the code to look like this:
$(document).on("click", ".removeruleset", function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
But that gives me the following error :
SCRIPT438: Object doesn't support property or method 'on'
I'm using version 1.5.2.
So, I referred to the article that's mentioned in some of the comments (Event binding on dynamically created elements?) and tried this instead:
$("body").delegate("click", ".removeruleset", function(e){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
That got rid of the error message but the event handler is still not triggered
Also tried:
$("body").on("click", ".removeruleset", function(e){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
Thanks.
Try this:-
$(document).on("click", ".removeruleset", function(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
});
When you added the event to the element it was not existing. To make this work you need to use event delegation.
hi another way is to do this htmlstring = htmlstring + '<td><input type="button" value="Remove" class="removeruleset"click=\"myhandler\"/></td>'
where myhandler is a function
function myhandler(){
alert('inside');
id = $(this).closest('tr').attr('id');
alert(id);
}
you can try this for dynamic control.
$('#id').live('click', function() {
----your code--
})
else you can try this:
>>>$(document).on('click','#id', function() {
-----your code ---
})

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources