This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
After executing a query, a table row is added, good, it gives the user the option to delete that row with a Delete button, here is when things start to get fussy, any function related to the appended tr just won't work,even when I changed the button.click to a whole tr, it deletes the headers tr and every other table tr except for the appended ones!
Just to clarify, the table is inside a form that is not #codbar
$('#codbar').submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: "/GoogleStore/ajax/venta.php",
data: {'iditem': $('#id-item').val()},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr)
{
var i = 0;
var end = parseInt($('input[name = "contador"]').val());
for(i = 0; i <= end; i++)
{
if($('input[name = "cod'+i+'"]').length && $('input[name = "cod'+i+'"]').val() == data["Cod"])
{
$('input[name = "cant'+i+'"]').val(parseInt($('input[name = "cant'+i+'"]').val()) + 1);
$('span[name = "total'+i+'"]').text(parseFloat($('input[name = "cant'+i+'"]').val()) * parseFloat($('input[name = "precio'+i+'"]').val()));
i = end;
}
else if(i == end)
{
$('input[name = "contador"]').val();
$('table[name = "venta"]').find('tbody').append($('<tr><td><span>'+data["Prod"]+'</span></td><td><input type="hidden" name="cod'+i+'" value="'+data["Cod"]+'"><span>'+data["Cod"]+'</span></td><td><input type="text" name="cant'+i+'" value="1"></td><td><input type="hidden" name="precio'+i+'" value="'+data["Precio"]+'"><span>'+data["Precio"]+'</span></td><td><span name="total'+i+'">'+data["Precio"]+'</span></td><td><input type="button" class="red" name="DeleteRow" value="Eliminar"></td></tr>'));
$('input[name = "contador"]').val(end + 1);
}
}
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
});
$("input[name = 'DeleteRow']").click(function()
{
alert('');
$(this).closest('tr').fadeOut('slow', function()
{
$(this).closest('tr').remove();
});
});
You need to delegate the event to the static parent:
$(document).on('click', "button[value = 'Eliminar']", function()
change to this as above.
Because you are appending the tr dynamically so any event registered on static elements won't be bound on newly created element.
Try this
$("table[name = "venta"]").on("click","button[value = 'Eliminar']",function()
{
alert('');
$(this).closest('tr').fadeOut('slow', function()
{
$(this).closest('tr').remove();
});
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I'm aware similar questions have been asked and answered but I can't seem to get them to apply to my issue.
Below is the code that sends an ajax post when the form is submitted
$form.on("submit", function(event) {
event.preventDefault();
$.ajax({
url: url,
data: JSON.stringify({ description: desc }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function(data) {
$(".list").append(
'<li><input type="checkbox" value="' +
data.id +
'">description</li>"
);
createOnClicks(data.id);
},
error: function(error) {
//list errors },
complete: function() {
//reset form
}
});
});
this is part of the createOnClicks() function:
function createOnClicks(id) {
var listId = "#" + id;
$(listId).on("click", function(event) {
var value = $(this).is(":checked");
if (value) {
console.log("checked");
$.ajax({
url: "/listapi/" + id + "/complete",
type: "POST",
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log(data);
$(listId)
.parent("li")
.addClass("complete");
}
});
} else { ...
}
});
createOnClicks works correctly when it is called on elements that are there when the page loads, but won't work on elements that are added with the ajax post.
$(listId) returns an empty object when called within createOnClicks(), despite on the line above `console.log(listID) shows the appropriate value.
This should apply a click handler to all elements with matching selector even if added after pageload.
$(document).on('click', '#list_id', (event)=>{/* some code */})
Per comments, this should help do what you need:
<html>
<body>
<button id="add">add</button>
<div id="container">
</div>
<script type="text/javascript">
var postHandler = (event)=>{
console.log('my id is', event.currentTarget.getAttribute('data-postid'));
}
var number_of_elements = 0;
document.getElementById('add').addEventListener('click', (event)=>{
let new_element = document.createElement('div');
new_element.innerText = "hello";
new_element.className = "cool_element";
new_element.setAttribute('data-postid', number_of_elements++);
new_element.addEventListener('click', postHandler);
document.getElementById('container').appendChild(new_element);
})
</script>
</body>
</html>
I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!
When you click the button when the display of a content, and then click the button when the content hidden, and then click the button when the show repeat, I do not know how to solve the problem? Big god can help solve? Thank you very much!
HTML file
<button id="liuyan" type="button" class="btn btn-primary btn-lg">my click</button><div id="mydiv2">
JavaScript file
$("button#liuyan").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:3000/api/comment',
method: 'GET',
dataType: "jsonp",
async: false,
}).done(function(data, textStatus, jqXHR) {
var mydiv2 = $("#mydiv2");
if (mydiv2.css("display") === "none") {
mydiv2.show();
var mycode = document.createElement('div');
mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
Rainbow.color(mycode, function() {
document.getElementById('mydiv2').appendChild(mycode)
});
} else {
mydiv2.hide();
}
console.log(data);
console.log(jqXHR.responseText);
});
});
I dont have AJAX URL. I gave dummy data. It should work.
Every time, while showing you are appending the content with existing content. So it will repeat. So you have to remove the existing content in div and append it to div.
Add this line before appending
document.getElementById('mydiv2').innerHTML = '';
Then existing content will get cleared.
$("button#liuyan").on("click", function(e) {
e.preventDefault();
data = {
"name":"hello"
}
var mydiv2 = $("#mydiv2");
if (mydiv2.css("display") === "none") {
mydiv2.show();
var mycode = document.createElement('div');
mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
//Rainbow.color(mycode, function() {
document.getElementById('mydiv2').innerHTML = '';
document.getElementById('mydiv2').appendChild(mycode)
//});
} else {
mydiv2.hide();
}
// console.log(data);
// console.log(jqXHR.responseText);
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="liuyan">Click</button>
<div id="mydiv2"></div>
Another Way:
You can make a call on ready function and show and hide when click on the button
i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.