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

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

Related

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

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

How to get the value from dynamically created checkbox using Jquery with class

I am trying to get the value from checkbox when checked which is created dynamically with jquery associated with html table am using class to get the value but am unable to get it
My code is like this
Input created with Jquery
"<td><div class=" + "checkbox checkbox-primary" + "><input type=" + "checkbox" + " class=" + "cbCheck" + " value=" + "" + data.d[i].Rowname + "" + "" + data.d[i].one + "" + "></div></td>"
Jquery to get the value
$("#table").on(":checked", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Please help me how to fix this.
Thanks in advance
Working Fiddle
Try:
$('table tr td').on('click','.cbCheck',function() {
if ($(this).is(':checked')) {
alert($(this).attr('id'))
}
else
alert('unchecked');
});
Use 'change' event:
$("#table").on("change", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Instead of creating it like that
use Create element and add id dynamically then use your function I guess it will work, actually worked in my case
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'ptworkinfo';
You can do using following for dynamically created elements:
$(document).on("click", ".cbCheck", function () {
var value=$(this).attr("value");
alert(value);
});

Dynamically building a button with an onClick

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.
I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".
Here is a code snippet of the construction as it stands.
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
Value="Go To Field"
onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
/>
</div>';
return structure;
};
This is outputting:
<button class="inputButton"
value="Go To Field"
onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>
As you can see, the quotations will not be out put correctly and so break on click.
Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.
Kind Regards.
As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).
1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
value="Go To Field" data-field="' + this._field.name + '"/>
</div>';
return structure;
};
2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:
$(document).on('click', '.inputButton', function() {
var $button = $(this);
var field = $button.data('field');
goToFieldFromAlert('input[name="' + field + '"]');
});
You should create element using jQuery. This is much cleaner and error free approach
An example with your code
InvalidField.prototype.getMessageStructure = function(){
var structure =
$('<div></div>').append(
$('<span></span>').text(this._message)
);
structure.append(
$('<button></button>')
.addClass('inputButton')
.text("Go To Field")
.click(function(){
goToFieldFromAlert($(this._field.selector));
})
);
return structure;
};
The following example will dynamically add buttons:
hello.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = value; // some value
card.style.backgroundColor="#5ABC7B";
document.body.appendChild(card);
});

How do I read dynamic data passed in an event handler in dynamic table

I am dynamically constructing table rows using jquery.
In the following chunk of code, how do I read someValue in method prepareDiv()?
$( document ).ready(function() {
var someValue = "DummyValue"
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td><a href="#" onclick="prepareDiv('+ someValue +');"><img src="../images/downarrow.jpg"></td></tr>';
$('#resTable tr').first().after(html);
});
function prepareDiv(value){
alert("value" + value);
}
I am using IE. Upon calling ready(), I get error DummyValue is undefined.
The problem is that you're ending up with generated code that looks like this:
onclick="prepareDiv(DummyValue);"
The lack of quotes around DummyValue means that it's expected to be a variable, whereas you want it to be treated as a string literal, so you need to add the quotes yourself:
onclick="prepareDiv(\''+ someValue +'\');"
That should result in:
onclick="prepareDiv('DummyValue');"
Just do something like this...the dynamically added values should be appended to tbody
var table = $("table tbody");
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
firstVal= $tds.eq(0).text(),
secVal = $tds.eq(1).text(),
thirdVal = $tds.eq(2).text();
alert(firstVal);//etc..
});
You have fews syntax errors, try this:
$( document ).ready(function() {
var someValue = "DummyValue";
html += '<tr id="resRowId' + rowindex + '" class="RsrvnRowClass">' +
'<td>' + '<img src="../images/downarrow.jpg" /></td></tr>';
$('#resTable tr').first().after(html);
});

Calling function from button not working for html created using javascript

I am using javascript to create html page , but not able to call some function on button click .
var alernative = "plot1";
var buttonvalue= "mybutton";
function callme()
{alert("hello");}
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' + callme() + '";></div>');
In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .
Hoping for Suggestion or some help .
You need to pass the function name as a part of the string:
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
It is a bad practice to write HTML with strings, DOM exists for one reason!
var input = $('<input/>', {
type: "button",
style: "float: right",
value: buttonValue
}),
element = $('<div/>').append(input);
input.click(function () {
callme();
});
$('#test').html(element);

Categories

Resources