I would like to add a doubleclick event handler to table cell AFTER the table was "downloaded" from a servlet and "inserted" by javascript.
I have a javascript cycle that iterate on a xml response to map datas ini table. Said that a cell can be
<td class='red' ></td>
I want to add a function on that cell, I've tried several solution, but none works.One is:
$(".red").on("dblclick",myfunction);
Help?
Update:
Table constructor ofter response received
function handleResponse(responseXML) {
var i;
var x=responseXML.getElementsByTagName("row");
var out="<table><tr><th >Description</th><th >State</th><th>Note</th></tr>";
for(i=0;i<x.length;i++){
out+="<tr>";
var Description = x[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var State = x[i].getElementsByTagName("State")[0].childNodes[0].nodeValue;
var note = x[i].getElementsByTagName("Note")[0].childNodes[0];
var note_text=" ";
if (!(typeof note === "undefined") && !(note=='null')) {
note_text=note.nodeValue;
}
out += "<td>"+Description+ "</td>";
if(State==0)
out+="<td class='white' ></td>";
else if(State==1)
out+="<td class='red' ></td>";
else if(State==2)
out+="<td class='yellow' ></td>";
else if(State==3)
out+="<td class='green' ></td>";
out+="<td>" + note_text + "</td></tr>";
}
var output = document.getElementById("mytable");
out+="</table>";
$().on("click",".red",update()); //here is the point
output.innerHTML=out;
}
Update:
Based on your comments you can try this:
When you print the td change the template a little:
out+="<td class='red' ondblclick='openModal()'></td>";
And then in your js file add something like this.
$(document).ready(function() {
function openModal() {
alert( "Double clicked." );
// Or call your other function here...
};
});
You can do it with several ways also, check here: http://www.w3schools.com/jsref/event_ondblclick.asp
Related
I'm building a page that makes an Ajax call to retrieve a .csv file, and load the values into an HTML table. I call it in a $(document).ready(function(){ ltm.init(); }); call at the bottom of the HTML file.
It loops over the rows of the CSV file, and constructs an HTML table in a javascript variable, then hands the table off to the DOM using $('#myTable').html(table_data). The next function, ltm.convertTableToDataTable() uses $('#myTable').DataTable() to convert it to a simple DataTable. However, it's not firing. I added a button to call the convertTableToDataTable() function, and when I click it, it works fine, and the DataTable is fully functional.
If I put an alert() in the convertTableToDataTable immediately before the $('#myTable').DataTable(), the alert displays, and the table converts properly. If I move the alert to after the .DataTable() call, the alert displays, and the table does not convert.
I've tried using setTimeout($('#myTable').DataTable(),5000); to introduce a delay before the .DataTable() call, but that doesn't work either.
How can I get this to load in the data and create a DataTable thing on my page without the alert?
Here's my genericized javascript snippet:
var ltm = {
// local variables
urlCSV: 'myData.csv',
init: function() {
ltm.loadCSVDataIntoTable();
//alert('convertTableToDataTable fired!');
ltm.convertTableToDataTable();
// Bind click events
$('#btnLoadCSVData').click(function() {
ltm.loadCSVDataIntoTable();
});
$('#btnMakeDataTable').click(function() {
ltm.convertTableToDataTable();
});
},
loadCSVDataIntoTable: function() {
// The URL contains the .csv file. The first row of the file is the column headers.
$.ajax({
url:ltm.urlCSV,
dataType:"text",
success:function(csvData) {
var my_data = csvData.split(/\r?\n|\r/);
// var table_start = '<table class="table table-bordered table-striped" id="tblLTMStrains">';
var table_start = '<table class="display" id="tblLTMStrains">';
var table_end = '</table>';
var table_head_start = '<thead><tr>';
var table_head_end = '</tr></thead>';
var table_head = '';
var table_foot_start = '<tfoot><tr>';
var table_foot_end = '</tr></tfoot>';
var table_body_start = '<tbody>';
var table_body_end = '</tbody>';
var table_rows = '';
var table_data = '';
for(var intRow = 0; intRow<my_data.length; intRow++)
{
if (intRow===0) { // First row contains column headers
var cell_data = my_data[intRow].split(",");
for(var cell_intRow=0; cell_intRow<cell_data.length; cell_intRow++)
{
table_head += '<th>'+cell_data[cell_intRow]+'</th>';
}
} else {
if (my_data[intRow].length > 0) { // Gracefully handle null lines
var cell_data = my_data[intRow].split(",");
var blnLoadRow = true;
if ([Some conditions under which I want to filter out the row]) {
blnLoadRow = false;
}
if (blnLoadRow){
var thisRow = $('#templateDataRow').html();
// Can't put the <tr> content in a DIV without it stripping out all the tags
// Also, even if I don't put a <tbody> in, the DOM will create one anyway, so strip it out too.
thisRow = thisRow.replace("<table>","");
thisRow = thisRow.replace("<tbody>","");
thisRow = thisRow.replace("</tbody>","");
thisRow = thisRow.replace("</table>","");
thisRow = thisRow.replace("__MYFIELD0__",cell_data[0]);
thisRow = thisRow.replace("__MYFIELD1__",cell_data[1]);
thisRow = thisRow.replace("__MYFIELD2__",cell_data[2]);
thisRow = thisRow.replace("__MYFIELD3__",cell_data[3]);
thisRow = thisRow.replace("__MYFIELD4__",cell_data[4]);
table_rows += thisRow;
}
}
}
}
table_data = table_start;
table_data += table_head_start + table_head + table_head_end;
table_data += table_foot_start + table_head + table_foot_end;
table_data += table_body_start + table_rows + table_body_end;
table_data += table_end;
$('#divMyTable').html(table_data);
}
});
},
convertTableToDataTable: function() {
//alert('convertTableToDataTable fired - BEFORE!');
$('#myTable').DataTable();
//alert('convertTableToDataTable fired! - AFTER');
},
lastFunction: function() {} // all previous closing curly braces should have a comma after them
} // end of the ltm object.
change
$('#divMyTable').html(table_data);
to
$('#divMyTable').html(table_data).onload().DataTable();
this will make sure, DataTable is fired when html is loaded.
and remove the
convertTableToDataTable: function() {
//alert('convertTableToDataTable fired - BEFORE!');
$('#myTable').DataTable();
//alert('convertTableToDataTable fired! - AFTER');
},
I am trying to reformat the table by doing some changes in the existing table in my application. I have searched on internet for below error but I haven't found any solution for this.
Error I am getting is as below:
Cannot read property 'createDocumentFragment' of undefined
Here is my
function editTable()
{
// debugger;
// remove blank td pair
$('#prodHold tr td').each(function() {
// debugger;
if ($(this).text() == ''){
$(this).prev('td').remove();
$(this).remove();
}
});
// get array of all tds
var tds = $('#prodHold tr td').length;
var td_arr = [];
for(var i=0; i<tds; i++){
// if($(this).text()!== ''){
// td_arr.push($('#prodHold tr td').eq(i).html());
// }
if($(this).html()!== ''){
td_arr.push($('#prodHold tr td').eq(i).html());
}
}
// prepare table, wrap tr for every 4 tds, *according to your table sample
var e = '<tr>';
for(var i=1; i<=td_arr.length; i++){
if(i%4 == 0){
e = e + '<td>' + td_arr[i-1] + '</td></tr><tr>';
}
else{
e = e + '<td>' + td_arr[i-1] + '</td>';
}
}
// append
$('#prodHold').html(e);
}
$(document).ready(function () {
editTable();
});
Getting error on below line
td_arr.push($('#prodHold tr td').eq(i).html());
Code I am using from the question posted on below
Remove content from table and reformat the table
Please guide me If I am doing anything wrong here.
The error seems to be triggered on $(this).html(), because this does not refer to a DOM element. You are using this in a normal for loop, while you probably intended it to be used in a jQuery each loop callback.
Like this:
// get array of all tds
var tds = $('#prodHold tr td'); // not length
var td_arr = [];
tds.each(function() {
if($(this).html()!== ''){
td_arr.push($(this).html());
}
})
NB: You should really reconsider if the erroneous code you received as an answer deserved to be marked accepted.
I have a view with a table with single selection mode and a button in its toolbar to delete selected row.
Though when I press the button, it deletes all the rows instead.
My code:
View file:
<template data-controller-name="myapplication.myview2">
<div data-sap-ui-type="sap.ui.table.Table" id="tb1" data-width="100%" data-title="Person Table"></div>
</template>
Controller File:
onInit: function() {
try {
var oTab = [
// the table content
];
var oToolbar = new sap.ui.commons.Toolbar();
oToolbar.addItem(new sap.ui.commons.Button({text: "Delete selected row",
press: function() {
try {
var newTab = this.getParent().getParent();
var index = newTab.getSelectedIndex();
if (index == -1)
alert("No row selected");
else {
var currModel = newTab.getModel();
var selectedRow = newTab.getRows()[index];
newTab.removeRow(selectedRow);
currModel.setData({table: newTab});
newTab.bindRows("/table");
}
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}}));
this.byId("tb1").setToolbar(oToolbar);
this.byId("tb1").setVisibleRowCount(5);
this.byId("tb1").setNavigationMode(sap.ui.table.NavigationMode.Paginator);
// Columns definition should be HERE
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({table: oTab});
this.byId("tb1").setModel(oModel);
this.byId("tb1").bindRows("/table");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
},
// More functions....
Any ideas please?
You need to remove row from model, not from table directly.
Here is an example on how to do this.
http://jsbin.com/yewula/1/edit
Like many folks have suggested, we should removed it from the model. Since table is binded to the model, table will refresh accordingly.
-D
In your press function for the delete button, get more details about the table:
var tableIndex = newTab.getSelectedIndex();
var context = newTab.getContextByIndex(tableIndex);
var path = context.getPath();
In the variable path you will then find the data index that corresponds to the table row index. Use this data index to remove the row from the model.
currModel.oData.table.splice(data_index, 1);
Afterwards, all that should be needed is a refresh of the model to inform the controls about the changed data. And, for the user it might also be nice if the selection in the table gets reset as well.
currModel.refresh();
newTab.setSelectedIndex(-1);
First, hello everyone as I'm new here.
To summarize my problem, I read the content of an XML file to display in a table.
The basic function to do this works well, I created a derivated function to include a search filter related to an input field.
The search algorithm works well and I'm able to preview the HTML code of the search result using the alert() function and this code seems proper and can be displayed in a browser properly as it would be supposed to. However the innerHTML code of the concerned div is not updated...
I would appreciate any kind of input or solution anyone could provide as I've been stuck on this ! Thanks !
Here is the code :
function printListMod2(){
//Search parameters ?
var searchContent = document.getElementById("searchField").value;
var i=0;
newHTML = "<table id=\"tableInstrus\">";
for (i=0;i<listInstrus.length;i++){
filename = returnFilename(i);
title = returnTitle(i);
tempo = returnTempo(i);
sample = returnSample(i);
multi = returnMulti(i);
style1 = returnStyle1(i);
style2 = returnStyle2(i);
var regEx = new RegExp(searchContent, 'gi');
var resultSearch = title.match(regEx);
if(resultSearch!=null){
if(i%2==0){
newHTML += "<tr class=\"tr0\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
else{
newHTML += "<tr class=\"tr1\"><td class=\"idColumn\">"+(i+1)+"</td><td class=\"emptyColumn\"></td><td class=\"nameColumn\">"+title+"</td><td class=\"tempoColumn\">"+tempo+"</td><td class=\"sampleColumn\">"+sample+"</td><td class=\"multiColumn\">"+multi+"</td><td class=\"styleColumn\">"+style1+"</td><td class=\"styleColumn\">"+style2+"</td><td class=\"addLink\"><a id="+filename+" onclick=\"addLinkToPlaylist("+i+")\"><img title=\"Add to playlist\" class=\"addButton\" src=\"images/buttonAdd.png\"/></a></td><td class=\"playLink\"><a onclick=\"playTrack("+i+","+true+")\"><img title=\"Play this track\" class=\"playButton\" src=\"images/buttonPlaySmall.png\"/></a></td></tr>";
}
}
}
newHTML += "<tr><td class=\"idColumn\"></td><td id=\"emptyColumn\"></td><td class=\"nameColumn\"></td><td class=\"tempoColumn\"></td><td class=\"sampleColumn\"></td><td class=\"multiColumn\"></td><td></td><td></td></tr>";
newHTML += "</table>";
alert(newHTML); //this displays the HTML code properly
document.getElementById("listDiv").innerHTML = newHTML; //this doesn't seem to do anything...
}
Is your script being executed before the document has finished loading?
Then it won't find #listDiv because the div doesn't exist yet.
I would check the javascript console output for errors and check if the following code doesn't return undefined:
{
...
console.log( document.getElementById('listDiv') );
}
I am trying to populate an HTML table using the JSON string retrieved from a $.getJSON() call. The $.getJSON() call is working fine. But I am not able to populate an html table with the retrieved json data. Please help me with my code..I'm new to this..
function loadTable(result){
if(result.groups="no"){
var num_rows = result.noofteams;
var rows = "";
for(var i=0;i<num_rows;i++){
rows +='<tr>'+result.noofteams+'</tr>';
}
$("#container").append(rows);
Here result is the json object that i am receiving. result.noofteams is giving proper value (i have checked it). But the problem is, i am unable to populate #container with result.noofteams Please help..
u used = while u need == or === for conditions
function loadTable(result){
if(result.groups==="no"){
var num_rows = result.noofteams;
var rows = "";
for(var i=0;i<num_rows;i++){
rows +='<tr><td>'+result.noofteams+'</td></tr>';
}
$("#container").append(rows);
}
}
EDIT: Add <td> they are important as well
It's much cleaner to work with JSON like so...
for (i in result) {
rows += '<tr>' + result[i]['noofteams'] + '</tr>';
}