class not working perfectly on dynamically generated button jQuery, Bootstrap - javascript

I'm generating a table using jQuer, Ajax .
All the thing working fine but the edit button not working perfectly.
I want to copy all data-(properties) on click.
If I do the same with php it works fine, But I need using jquery.
here is my code.
==================== table code ===========
$("#get_spare_list").click(function() {
var ht = "";
$.ajax({
url: "<?php echo base_url('Spare/get_all_spare_json'); ?>",
type: 'POST',
dataType: 'json',
data: {"param1": 'value1'},
})
.done(function(data) {
var no = 1;
var ht = "<table class='table'><thead><tr><th>No</th><th>Name</th><th>Code</th><th>Min qty</th><th>uni</th><th>Group</th><th>Sub Category</th><th>Part Number</th><th>Location</th><th>Image</th><th>Barcode</th><th>Tyre</th><th>Back</th></tr></thead>";
$.each(data, function(key, val) {
ht +="<tr>"+"<td>"+no+"</td>"+"<td>"+val.name+"</td>"+"<td>"+val.code+"</td>"+"<td>"+val.min_qty+"</td>"+"<td>"+val.unit+"</td>"+"<td>"+val.group+"</td><td>"+val.sub_category+"</td><td>"+val.part_number+"</td><td>"+val.location+"</td>";
if (val.image) {
ht += "<td><a target='_blank' href='"+"<?php echo base_url('../images/'); ?>/"+val.image+"'><button class='fa fa-picture-o'></button></a></td>";
}else{
ht += "<td></td>";
}
ht += "<td><button class='btn btn-info btn-xs' onclick=PrintBar('val.code')>Print</button></td>";
ht +="<td>"+val.tyre+"</td>";
ht += "<td>";
if (val.reusable) {
ht +="yes";
}else{
ht+="no";
};
ht += "</td>";
ht += "<td><button class='btn edit btn-info btn-xs' data-toggle='modal' data-target='#editModel' data-id='"+val.id+"' data-name='"+val.name+"' data-code='"+val.code+"' data-min_qty='"+val.min_qty+"' data-unit='"+val.unit+"' data-group='"+val.group+"' data-sub_category='"+val.sub_category+"' data-part_number='"+val.part_number+"' data-location='"+val.location+"' data-tyre_number='"+val.tyre+"' data-back='"+val.reusable+"'><span class='fa fa-edit'></span></button></td>";
ht += "</tr>";
no++;
});
$("#js_res").append(ht);
console.log(ht);
})
.fail(function() {
alert("error");
});
});
======== Class code to copy data ============
$(".edit").click(function() {
$("#id").val($(this).data('id'));
$("#name").val($(this).data('name'));
$("#code").val($(this).data('code'));
$("#min_qty").val($(this).data('min_qty'));
$("#unit").val($(this).data('unit'));
$("#group").val($(this).data('group'));
$("#sub_category").val($(this).data('sub_category'));
$("#part_number").val($(this).data('part_number'));
var location = $(this).data('location');
var l1 = location.split("->");
$("#room").val($.trim(l1[0]));
$("#rake").val(l1[1]);
$("#line").val(l1[2]);
$("#box").val(l1[3]);
if ($(this).data('tyre_number')) {
$("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
}else{
$("input[name=tyre][value='']").prop('checked', true);
};
if ($(this).data('back') == "1") {
$("#back").attr('checked', true);
}else{
$("#back").removeAttr('checked');
};
});

Instead of click function you can use .on() function
$(document).on('click','.edit', function() { will bind the event on the .edit elements which are not present at the time of binding event. This is called event delegation
$(document).on("click", ".edit", function() {
// your code here
})

This is because the element is dynamically generated, so does not exist on initial page load.
Use $.fn.on()
From the documentation
$(staticAncestors).on(eventName, dynamicChild, function() {});
In your case, it would be:
$(document).on("click", ".edit", function() {
$("#id").val($(this).data('id'));
$("#name").val($(this).data('name'));
$("#code").val($(this).data('code'));
$("#min_qty").val($(this).data('min_qty'));
$("#unit").val($(this).data('unit'));
$("#group").val($(this).data('group'));
$("#sub_category").val($(this).data('sub_category'));
$("#part_number").val($(this).data('part_number'));
var location = $(this).data('location');
var l1 = location.split("->");
$("#room").val($.trim(l1[0]));
$("#rake").val(l1[1]);
$("#line").val(l1[2]);
$("#box").val(l1[3]);
if ($(this).data('tyre_number')) {
$("input[name=tyre][value=" + $(this).data('tyre_number') + "]").prop('checked', true);
}else{
$("input[name=tyre][value='']").prop('checked', true);
};
if ($(this).data('back') == "1") {
$("#back").attr('checked', true);
}else{
$("#back").removeAttr('checked');
};
})
For more detail on why this doesn't work, see: Event binding on dynamically created elements?

Related

How can I append modal button inside td using ajax script

I have problem inserting modal button inside my html table. I'm using AJAX and append built in function. I tried this approach
" Open modal"
but it did'nt work. I tried to remove the button properties like 'class', 'type' , etc and it worked but I need those. Any approach for this. Thank you.
This is my code
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({
type: "GET",
url: "getproducts/",
dataType: 'json',
data: {id: id},
success: function (response) {
var len = 0;
if(response['data'] !=null){
len = response['data'].length;
}
$('#userTable tbody').empty();
if(len > 0){
for(i = 0; i < len; i++) {
var p_id = response['data'][i].p_id;
var p_name = response['data'][i].p_name;
var p_amount = response['data'][i].p_amount;
var m_fname = response['data'][i].m_fname;
var tr_str =
"<tr>" +
"<td>" + p_id + "</td>"+
"<td>" + p_name + "</td>" +
// HOW CAN I ADD MODAL BUTTON HERE THIS APPROACH DOESN'T WORKED
"<td> <button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#myModal2">Open modal</button></td>"
"<tr>";
$('#userTable tbody').append(tr_str);
}
}
}
});
};
</script>
Expected output should be like this
I think the problem with string concatenation
I am giving a code. please replace it.
"<td> <button type='button' class='btn btn-primary' data-bs-toggle='modal'
data-bs-target='#myModal2'>Open modal</button></td>"

Unregister jquery event for <tr> in dynamic table [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I am working for dynamic table from a jquery/ajax function that will display a list of files depending on the clicked category.
Once the list of file is displayed, the user can click on table row (checkbox will also be checked) to display/preview the file but the row can't have a jquery event.
I have tried it on a plain html table with the function below and it worked.
What could be the solution for this?
function directoryAction(obj){
var directory = obj.value
var editDer = directory.replace("./","");
$(".content-main").html("<button class='btn btn-default'><i class='fa fa-folder-o'></i></button>"+
"<button class='btn btn-default' value='"+ directory +"' onclick='addDocument(this);'><i class='fa fa-upload'></i></button>");
$(".content-main").append("<h5>"+editDer+"</h5>");
$(".content-main").append("<table class='record_table'>"+
"<thead>"+
"<tr>"+
"<th class='check'><input type='checkbox' class='form-control '/></th>"+
"<th>File Name</th>"+
"<th>Uploader</th>"+
"<th>Date Modefied</th>"+
"</tr>"+
"</thead>"+
"<tbody class='fileTbody'></tbody></table");
var dataString = "directory=" + directory + "&getFileInDirectory="
$.ajax({
url: "main.php",
type: "GET",
data: dataString,
dataType: "json",
contentType: false,
cache: false,
processData: false,
success:function(data){
var id = 0;
$.each(data,function(i,element){
var fName = element.namef;
var uploader = element.uploader;
var datestamp = element.datestamp;
var fileId = element.id;
$(".fileTbody").append("<tr class='clickRow' id='"+ id + "'><td><input id='file"+ id +"' type='hidden' value='"+ fileId +"'>"+
"<input type='checkbox' id='chk"+ id + "' class='form-control'/></td>"+
"<td>"+ fName +"</td><td>"+uploader+"</td><td>"+datestamp+"</td></tr>");
id++;
});
}
});
}
$(function(){
$(document).ready(function() {
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
});
Change from
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
to
$('body').on('click', '.record_table tr', function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
or
$('.content-main').on('click', '.record_table tr', function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});

How to remove a table's row from jquery dialog table?

There is jquery dialog (#dialog-message1) where table (tableINFO) is append.
Each row of the table shows some information regarding product with a picture link in last column.
I would like to create an on-click event where some actions are taken i.e. table row deletion and (potrawy1Engine.php) script call.
I tried creating (.confirmation2),but it does not work as expected - link is followed instead.
Can somebody help me and advice on the js script, please?
What I would like to do is to delete a row in the table tableINFO, where a link was clicked after it was clicked.
.confirmation1 and .confirmation work fine, only .confirmation2 does not work.
Maybe the problem is that the table and the link are created dynamically in jquery?
Here is the js:
$("#dialog-message").hide();
$('.confirmation').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
$("#dialog-message").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
window.location.href = lnk;
},
Anuluj: function() {
$(this).dialog("close");
}
}
});
});
$("#dialog-message1").hide();
$('.confirmation1').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
var product_name = $(this).parents("tr").find("td").first().html();
$( "#dialog-message1" ).hide();
$( "#dialog-message1 table" ).remove();
$( "#dialog-message1 #labelINFO" ).remove();
$("#dialog-message1").append("<table id='tableINFO'> </table>");
$("#dialog-message1 table").append("<tr><th width='350px' >Nazwa produktu</th><th width='70px'>Waga (g)</th><th width='100px'>Kalorie (Kcal)</th> <th width='80px'>Białko (g)</th> <th width='90px'>Tłuszcze (g)</th><th width='120px'>Węglowodany (g)</th><th width='30px'> </th> </tr>");
$.ajax({
method: "POST",
url: "potrawyINFOEngine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
var len = result.length;
for(var i=0; i<len; i++){
var T_nazwaproduktu = result[i].produkt;
var T_waga = result[i].waga;
var T_kalorie = result[i].kalorie;
var T_bialko = result[i].bialko;
var T_tluszcze = result[i].tluszcze;
var T_weglowodany = result[i].weglowodany;
var tr_str = "<tr>" +
"<td align='left'>" + T_nazwaproduktu + "</td>" +
"<td align='right'>" + T_waga + "</td>" +
"<td align='right'>" + T_kalorie + "</td>" +
"<td align='right'>" + T_bialko + "</td>" +
"<td align='right'>" + T_tluszcze + "</td>" +
"<td align='right'>" + T_weglowodany + "</td>" +
"<td align='center'>" +
"<a href='usunProduktPotrawa.php?nazwaPotrawy=" + product_name + "&nazwaProduktu=" + T_nazwaproduktu + "' title='Usuń produkt' class='confirmation2'><img src='pictures/cross16.jpg' width='10' height='10' style='margin: 0px 0px' /></a>" ;
"</td>" +
"</tr>";
$("#dialog-message1 table").append(tr_str);
}
console.log(data);
});
$.ajax({
method: "POST",
url: "potrawyINFOOpisEngine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
console.log(result);
$("#dialog-message1").append("<label id='labelINFO'>" + result + "</label>");
$( "#dialog-message1" ).show();
});
$("#dialog-message1").dialog({
height: "auto",
width: 950,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
$( "#dialog-message1 table" ).remove();
$( "#dialog-message1 #labelINFO" ).remove();
}
}
});
});
$("#dialog-message2").hide();
$('.confirmation2').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
var product_name = $(this).parents("tr").find("td").first().html();
$( "#dialog-message2" ).hide();
$.ajax({
method: "POST",
url: "potrawy1Engine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
console.log(result);
$( "#dialog-message2" ).show();
});
$("#dialog-message2").dialog({
height: "auto",
width: 450,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
});
HTML part is here:
<div id="dialog-message" title="Usuwanie potrawy">
<p>
<span class="ui-icon ui-icon-help" style="float:left; margin:0 7px 50px 0;"></span>Czy chcesz usunąć wybraną potrawe?
</p>
<p>
Naciśnij OK aby kontynuować.
</p>
</div>
<div id="dialog-message1" title="Składniki i opis potrawy">
</div>
<div id="dialog-message2" title="Test">
</div>
Thanks in advance for your help.

get method in php not working using bootgrid

could you help me to solve this problem
i tried to pass the selected value to create query in bootgrid when an item selected in command edit but i have problem in get method this is my code
thanks
<?php
//include("formClient.php");
if (isset($_GET["id"])) { $ClientId = $_GET["id"]; } else { $ClientId=0; };
echo $ClientId;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script langauge="javascript">
var grid = $("#grid-data").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
cache: false
},
url: "clientdata.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.ClientId + "\"><span class=\"glyphicon glyphicon-pencil\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.ClientId + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
var id=$(this).data("row-id");
$.ajax({
url: '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>',
type: "GET",
data: ({id: id}),
success: function(data){
console.log(data);
alert(data);
}
});
}).end().find(".command-delete").on("click", function(e)
{
//alert("You pressed delete on row: " + $(this).data("row-id"));
var x;
if (confirm("Are you sure to delete this record?") == true) {
x = "OK";
} else {
x = "CANCEL";
}
if (x=="OK"){
//window.location.href="DeleteClient.php?id="+ $(this).data("row-id");
}
});
});
</script>

onclick call to function from submit input not working

Here is my submit button written dynamically through AJAX:
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
I am trying to rerun the updatefilters() function to change the items that are displayed. I imagine its a bit tough to conceptualize without seeing all the code...but essentially, all I need to do is run the function again on each click of the submit button...right now, its giving me a updatefilters is undefined error in firebug.
Heres my whole JS for reference
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var i = 0;
var page;
if(! page){
page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
});
There appears to be a few problems with this approach.
First, you're not actually calling the function in your onclick handler.
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
should be:
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters();' /></li"
Second, the updatefilters function isn't accessible from the global scope, which is where that anonymous function will be executed from. You'd have to move function updatefilters(ev, ui) outside the onload callback, perhaps to the top of your script block.

Categories