I'm loading a table dynamically using jQuery ajax, the rows of the table has "contenteditable=true", I'm trying to listen on blur event for every cell, so that it triggers a function to update that cell dynamically.
The problem is that the event blur isn't fired at all, I've tried different selectors(table,tbody, and finally the whole document), but all in vain.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src='jquery-1.8.3.js'></script>
<link rel="stylesheet" href='jquery-ui-1.8.7.custom.css' type="text/css">
<?php
include './datatable_include.php';
?>
<script type="text/javascript">
$(function () {
$.ajax({//create an ajax request to load_page.php
type: "GET",
url: "load_table.php",
dataType: "html", //expect html to be returned
success: function (response) {
$('#dataTable').find('tbody').html(response);
initDataTable('#dataTable', null);
}
});
});
$(document).bind("blur", "td", (function () {
// this code isn't reached
alert("ahoo");
var id = $(this).attr("id");
var name = $(this).attr("name");
var message_status = $("#status");
var value = $(this).text();
$.post('update_table.php', "id=" + id + "&" + name + "=" + value, function (data) {
if (data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function () {
message_status.hide()
}, 3000);
}
});
}));
</script>
</head>
<body>
<table id="dataTable" width="700px" >
<thead>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
try
$(document).bind("td").blur(function()
{
});
seems that table td isn't a standard focusable element so you can't blur it.
try to add the tabsindex property to each td
<td tabindex="1">focus on me</td>
the definition of bind function is as follows:
.bind( eventType [, eventData ], handler )
so, you should do:
$('td').bind('blur', function(){
//event handler statement goes here
});
And as mentioned by #paul roub in the comments above, you should be using live() function, as you are creating the td elements dynamically.
$('td').live('blur', function(){
//event handler statement goes here
});
Related
This is regarding an issue related to the dynamic html table row controls. I have 2 cascading dropdowns named tagId and tagName. I have successfully implemented the cascading dropdowns. But the issue is while I am adding new rows to the table dynamically, the cascading drop downs are not working any more, on child rows. But, it's working properly on the top row. Please help me to resolve this.
From PopulateTagName.jsp I am getting second dropdown values based on first dropdown value.
Code::
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<%
%>
<script>
function myFunction() {
var selected = document.getElementById("TagID").value;
if (selected != "Select Tag ID") {
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var doc = this.responseText;
var ar = doc.split(',');
var sel = document.getElementById('TagName');
document.getElementById("TagName").options.length = 1;
for( var i= 0; i< ar.length; i++){
var opt = document.createElement('option');
opt.innerHTML = ar[i];
opt.value=ar[i];
sel.appendChild(opt);
}
}
};
xmlhttp.open("POST","PopulateTagName.jsp?TagID="+selected , true);
xmlhttp.send();
}
}
$(document).ready(function(){
$('#addRow').click(function(){
var sno=$('#pTable tr').length;
trow= "<tr><td class='sNo'>"+sno+"</td>"+
"<td><select name='TagID' id ='TagID' onchange='myFunction()'><option value='Select Tag ID'>Select Tag ID</option><option value='test1'>test1</option><option value='test2'>test2</option><option value='test3'>test3</option><option value='test4'>test4</option></select></td>"+
"<td><select name='TagName'><option value ='Select Tag Name'>Select Tag Name</option></select></td>"+
"<td><input name='TagValue' type='text'></td>"+
"<td><button type='button' class='rButton'>Remove</button></td></tr>";
$('#pTable').append(trow);
});
});
$(document).on('click', 'button.rButton', function () {
$(this).closest('tr').remove();
arrangeSno();
return false;
});
function arrangeSno(){
var i=0;
$('#pTable tr').each(function() {
$(this).find(".sNo").html(i);
i++;
});
}
</script>
<table id="pTable">
<tbody>
<tr>
<td>Serial No</td>
<td>*Select Tag ID:</td>
<td>Select Tag Name:</td>
<td>Input Tag Value:</td>
<td><input id="addRow" type="button" value="Add"></td>
</tr>
</tbody>
</table>
</body>
</html>
For the pre generated DOM it works with the
$('#addRow').click(function(){
But for the newly added DOM elements it works only with the .live function rather than .on so you must write your code as
$(document).live('click', '#addRow', function () {
Note : I can't regerate your issue on my machine but although ran into the same issue a long ago. And here's the solution. :)
Referencing to the Datatables API.
I implemented individual column searching and need to extend it:
There is a column which is displaying a button with HTML-Attributes/Classes applied. The Problem: I need to strip HTML in order to search the button's caption only. Any ideas how can I do that?
Here's my code:
table().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function (e) {
if (e.which == 27) {
$(this).val('');
}
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
I believe, you may need to employ external (custom) search function $.fn.DataTable.ext.search in order to look for button texts only (if that's what you're trying to achieve).
You may find the demo below:
//Sample source data
const srcData=[
{title:'apple',cat:'fruit',score:'good'},
{title:'strawberry',cat:'berry',score:'good'},
{title:'broccoli',cat:'vegie',score:'bad'},
{title:'durian',cat:'fruit',score:'bad'}
];
//Global variable for button text custom search
var buttonText = '';
//DataTables initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: [
{title: 'title', data: 'title'},
{title: 'category', data: 'cat'},
//render score property as a button
{title: 'score', data: 'score', render: (data, type, row, meta) => `<button>${data == 'good' ? 'Love it!' : 'Hate it!'}</button>`}
],
});
//Append <tfoot> and searchbars
$('#mytable').append('<tfoot><tr></tr></tfoot>');
dataTable.columns().every(function () {
$('#mytable tfoot tr').append(`<td><input colindex="${this.index()}"></input></td>`);
});
//Custom search function across button text only
$.fn.DataTable.ext.search.push((settings, row, rowIndex, rowData, counter) => $(dataTable.row(rowIndex).node()).find('td:eq(2) button').text().toLowerCase().includes(buttonText) || buttonText == '');
//Listen for 'keyup' in <tfoot> searchbars
$('#mytable').on('keyup', 'tfoot td input', function () {
const colindex = $(this).attr('colindex');
//If it's input in 3-rd column (colindex==2)
//simply assign global variabl and re-draw
//table to apply custom search
if (colindex == 2) buttonText = $(this).val().toLowerCase();
//Otherwise search by corresponding column
else dataTable.column(colindex).search($(this).val());
dataTable.draw();
});
tfoot td {
padding-left: 10px !important
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>
I am using jquery chosen and calling ajax on change drop down but records are not displaying. This code which I am using after changing drop down.
$.ajax({
type: "POST",
url: "MY URL",
data: {
sno: $(this).val()
},
success: function (resp) {
var resp = jQuery.parseJSON(resp);
if (resp.length == 0) {
$("#site").html('<option value="0" selected>Select Site</option>');
} else {
$.each(resp, function (i, item) {
$('#site').append($('<option>', {
value: item.siteNameID + '-' + item.siteName,
text: item.siteName
}));
});
}
},
error: function (resp) {
console.log('error');
}
});
One thing I have noticed jquery chosen applying on my select box but data which I am fetching from server side is not adding in that select box
You will need to call the chosen update trigger after you add items to your select list dynamically in order for them to show up. Use the following line after you have appended items and they should be displayed in your list.
$('#site').trigger("chosen:updated");
I think my code is not the answer for your question, but this mimics adding options to select... just click the add button...
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="add()">Add</button>
<select id="select"></select>
<script>
var json = [{title:"lorem",value:1},
{title:"john doe",value:2},
{title:"foo",value:3},
];
function add(){
$("#select").empty();
for(var x = 0; x<json.length; x++){
var option = '<option value="'+json[x].value+'"> '+json[x].value+'-'+json[x].title+'</option>';
$("#select").append($(option));
}
}
</script>
</body>
</html>
I have this code to create datatable with datatables.net plugin:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link type="text/css" href="https://cdn.datatables.net/1.10.3/css/jquery.dataTables.css" />
<link type="text/css" href="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.css" />
<script src="https://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type='text/javascript' src="https://datatables.net/release-datatables/extensions/KeyTable/js/dataTables.keyTable.js"></script>
</head>
<body>
<script type="text/javascript">
// function day2Date( day, year ) {
// return new Date(year,0,day);
//}
$(document).ready(function() {
$('#example').dataTable({
"ajax": "table1.php",
"columns": [{
"data": "ID"
}, {
"data": "naziv"
}, {
"data": "vrsta"
},
],
"columnDefs": [{
"targets": 2,
"data": "download_link",
"render": function(data, type, full, meta) {
// return data;
return '<button class="btn btn-success">' + data + '</button>';
}
}]
});
});
var table = $('#example').DataTable();
$(document).ready(function() {
$('#example tbody').on('click', 'td', function() {
console.log('Data:' + $(this).html().trim() + 'Row:' + $(this).parent().find('td').html().trim() + 'Column:' + $('#example thead tr th').eq($(this).index()).html().trim());
// alert('Row:'+$(this).parent().find('td').html().trim());
//alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim());
});
$('#example tbody').on('click', 'tr', function() {
console.log('Row index: ', table.row(this).index());
});
});
</script>
<div class="container">
<table id="example" class="table table-striped table-bordered table-responsitive" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Naziv</th>
<th>Vrsta</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Naziv</th>
<th>Vrsta</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
I need to get row index so I write as you can see from code above:
$('#example tbody').on( 'click', 'tr', function () {
console.log( 'Row index: '+table.row( this ).index() );
like I see on documentation on datatables web site but this code return me only [object Object]
example:
Data:12Row:2Column:Naziv
Row index: [object Object]
Why? Sombody have explanation?
You have included one key line of code outside any DOM ready handler, but before the element to which it occurs. That means that $('#example') is not returning a match:
Put this line in the DOM ready handler:
var table = $('#example').DataTable();
e.g
$(document).ready(function () {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'td', function () {
console.log('Data:' + $(this).html().trim() + 'Row:' + $(this).parent().find('td').html().trim() + 'Column:' + $('#example thead tr th').eq($(this).index()).html().trim());
// alert('Row:'+$(this).parent().find('td').html().trim());
//alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim());
});
$('#example tbody').on('click', 'tr', function () {
console.log('Row index: ', table.row(this).index());
});
});
When you do a String concatenation on a JavaScript Object it will implicitly call toString() on the Object.
The default Object.toString() simply returns [object Object].
To print out the contents of the Object use console.log with two arguments:
console.log( 'Row index:', table.row( this ).index() );
If I test on the DataTable example website then it appears to work as expected, and the result is a Number, so I think there must be some information missing from your question...
var table = $('#example').DataTable()
> []
table.row(1).index()
> 1
Hello I have the following on a page and I would like to pull the value: 36424. the value will change thus Im trying to create a function that will pull it when i call on the function.
<table cellspacing="0" cellpadding="3" rules="cols" border="1"
id="OSDataCount" style="color:Black;background-color:White;border-
color:#999999;border-width:1px;border-style:Solid;border-collapse:collapse;">
<tr style="color:White;background-color:Black;font-weight:bold;">
<th scope="col">COUNT(*)</th>
</tr><tr>
<td>36424</td>
</tr>
</table>
cheers
No need for jQuery:
var table = document.getElementById('OSDataCount');
alert(table.rows[1].children[0].innerHTML); // -> 36424
See example →
Using jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>
function alertval() {
var htmlval = $('#OSDataCount tr:eq(1)>td:first').html();
var textval = $('#OSDataCount tr:eq(1)>td:first').text();
alert("Val:" + val);
}
</script>
See http://api.jquery.com/text/, http://api.jquery.com/html/
Using raw JavaScript:
function alertval() {
var el = document.getElementById("OSDataCount");
alert("Val:" + el.rows[1].cells[0].innerHTML);
}
Adding a little detail to previous (correct) answers:
<script type="text/javascript">
window.onload = function() {
var table = document.getElementById('OSDataCount');
var number = table.rows[1].cells[0].innerHTML;
alert (number);
}
</script>
var value = document.evaluate('id(OSDataCount)/tr/td', document, null, XPathResult.NUMBER_TYPE);
going off a quick search/reach. Probably won't work, but worth a try.