Why can't I bind this onclick event? - javascript

I'm producing buttons for editing and removing each element in a Firebase database dynamically with javascript. And when there is only one element in the database (these elements represent polls/elections), the below code works fine. But when there is more than one database element, and hence more than one row of buttons, only the final pair of edit/remove buttons added are actually bound with the click event, which I suppose means all previous bindings are being overwritten in some way? I should also mention that both pollsRef.once() and pollsSnapshot.forEach() are asynchronous function calls (as are all Firebase API calls). Here is the function which creates and binds the buttons. ...
function displayCurrentPollsForEditing(pollsRef)
{
var tbl = createTable();
var th = ('<th>Polls</th>');
$(th).attr('colspan', '3');
$(th).appendTo($(tbl).children('thead'));
pollsRef.once('value', function(pollsSnapshot) {
pollsSnapshot.forEach(function(pollsChild) {
var type = pollsChild.name();
// If this is true if means we have a poll node
if ($.trim(type) !== "NumPolls")
{
// Create variables
var pollRef = pollsRef.child(type);
var pollName = pollsChild.val().Name;
var btnEditPoll = $('<button>EDIT</button>');
var btnRemovePoll = $('<button>REMOVE</button>');
var tr = $('<tr></tr>');
var voterColumn = $('<td></td>');
var editColumn = $('<td></td>');
var rmvColumn = $('<td></td>');
// Append text and set attributes and listeners
$(voterColumn).text(pollName);
$(voterColumn).attr('width', '300px');
$(btnEditPoll).attr({
'class': 'formee-table-button',
'font-size': '1.0em'
});
$(btnRemovePoll).attr({
'class': 'formee-table-remove-button',
'font-size': '1.0em'
});
$(btnEditPoll).appendTo($(editColumn));
$(btnRemovePoll).appendTo($(rmvColumn));
// Append to row and row to table body
$(tr).append(voterColumn).append(editColumn).append(rmvColumn);
$(tr).appendTo($(tbl).children('tbody'));
// Append table to div to be displayed
$('div#divEditPoll fieldset#selectPoll div#appendPolls').empty();
$(tbl).appendTo('div#divEditPoll fieldset#selectPoll div#appendPolls');
$(btnEditPoll).click(function() {
displayPollEditOptions(pollRef);
return false;
});
$(btnRemovePoll).click(function() {
deletePoll($(this), pollsRef);
return false;
});
}
});
});
}
The buttons are just rendered in a programmatically generated table, all the jQuery selectors are correct.

Related

How to get checked rows' values from html table on a sidebar using GAS?

I have a table whose rows consist of 3 columns. 1º is a checkbox, 2º contains the colors and the 3º contains the hex.
As the user selects the colors desired by ticking the checkboxes, i imagine the colors being pushed into an arrat, that will be written to a cell as the user clicks on the save button.
I've borrowed this snippet from Mark, but it doesn't seem to run in my context:
var checkboxes = document.getElementsByTagName("input");
var selectedRows = [];
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
selectedRows.push(secondColumn);
};
console.log(selectedRows)
}
This is the javascript part running to load and populate the table and I'm not sure where the above snippet woud go into:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
/**
* Run initializations on sidebar load.
*/
$(function() {
// Assign handler functions to sidebar elements here, if needed.
// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run
.withSuccessHandler(function (record) { //<-- with this
showRecord(record);
})
.withFailureHandler(
function(msg, element) {
showStatus(msg, $('#button-bar'));
element.disabled = false;
})
.getRecord();
});
/**
* Callback function to display a "record", or row of the spreadsheet.
*
* #param {object[]} Array of field headings & cell values
*/
function showRecord(record) {
if (record.length) {
for (var i = 0; i < record.length-1; i++) {
// Adds a header to the table
if(i==0){
$('#sidebar-record-block').append($($.parseHTML('<div class="div-table-row"><div class="div-table-header">Sel</div><div class="div-table-header">Color</div><div class="div-table-header">Hex</div></div>')));
}
// build field name on the fly, formatted field-1234
var str = '' + i;
var fieldId = 'field-' + ('0000' + str).substring(str.length)
// If this field # doesn't already exist on the page, create it
if (!$('#'+fieldId).length) {
var newField = $($.parseHTML('<div id="'+fieldId+'"></div>'));
$('#sidebar-record-block').append(newField);
}
// Replace content of the field div with new record
$('#'+fieldId).replaceWith('<div id="'+fieldId+'" class="div-table-row"></div>');
$('#'+fieldId).append('<input type="checkbox" class="div-table-td" id=CB"'+fieldId+'"name="checkBox" </input>')
.append($('<div class="div-table-td">' + record[i].heading + '</div>'))
.append('<div class="div-table-td">' + record[i].cellval + '</div>')
}
}
}
</script>
Sample of how to get the checked tickboxes an button click
Assuming all your checkboxes are tied to a row, you can loop through all checkboxes with a query selector,
access their checked status
and save the indices of those checkboxes.
Those indices will be the same as when looping through the corresponding table rows.
Sample implementing a button click event:
var saveButton = document.getElementById("myButtonId");
saveButton.onclick = function(){
var checkedRowIndices = [];
$('input[type=checkbox]').each(function( index ) {
if($(this)[0].checked{
checkedRowIndices.push(index);
}
});
};
//now get the rows with those indeices and do something with them

how to use $(this) with foreach in javascript using jquery

I am working on a personal project in Javascript to allow people to create a table of "dream plays" in Scrabble. Here is the link: http://psyadam.neoclaw.net/tables8.html
I am currently trying to allow the user to edit a dream play.
Here is my code:
function editRow(e)
{
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
$(this).children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success"
$(this).addClass('selected')
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
// insertRow assumes that the correct row in the table has the "selected" class added to it
function insertRow()
{
var Row = $('<tr>').append(
$('<td>').append('<input id="input1">'),
$('<td>').append('<select id="input2"><option value=""></option><option value="Yes">Yes</option><option value="No">No</option></select>'),
$('<td>').append('<select id="input3"><option value=""></option><option value="Natural">Natural</option><option value="1 Blank Used">1 Blank Used</option><option value="2 Blanks Used">2 Blanks Used</option></select>'),
$('<td>').append('<select id="input4"><option value=""></option><option value="vs Computer">vs Computer</option><option value="Online Game">Online Game</option><option value="Friendly Game">Friendly Game</option><option value="Club Game">Club Game</option><option value="Tournament Game">Tournament Game</option></select>'),
$('<td>').append('<input id="input5">')
)
$("#myTable tr.selected").after(Row)
}
Right now I'm just trying to get my code to insert a row into the table. I am trying to do this by using the code $(this).addClass('selected') to tag the row the user selected and then use it in my insert function to insert a row. However, nothing seems to happen. I am using pageEnd.innerHTML += "success" as a debugging tool to see if it is even getting there. Unexpectedly, it prints success twice when it should only print once, as in the test I ran every word was unique.
In any case I can't figure out why it's not working. Any help is appreciated. Thanks, ~Adam
You have two options to achieve this:
The first one as the others are suggesting i.e. by keeping a variable of outer this and then using this:
$('tr').each(function() {
var outerThis = this;
// inside another loop (not sure about children method, just an example)
$(outerThis).children("td:contains(test)").each(function() {
// do something with outerThis to operate on further
});
});
Another option to use Javascript's bind() method:
$('tr').each(function(i, trElement) {
// this == trElement
// inside another loop
$(outerThis).children("td:contains(test)").each(function(index, tdElement) {
$(this) // will be now tr element
$(tdElement) // will be td element
}.bind(this));
});
Try this:
function editRow(e) {
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
var outerThis = this;
outerThis.children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success";
$(this).children().css('text-align', 'center');
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
I set the outer this to a variable which you can use. Also textAlign is not a jQuery function. You need to use .css() and then specify text-align in that.

Kendo grid - get current editing row

How do you get the current row that's been edited even when it's not selected? I have a batch enabled Kendo grid that is navigatable. My goal is to manually edit data in a column using the dataItem.set() method. However, when you add a row it does not get selected automatically. Hence, vm.testGrid.dataItem(vm.testGrid.select()) cannot be used.
vm.testGrid.dataSource.get(e.model.get("Id")) gets the newly added row, but if multiple rows were added before saving, it will always get the first added row ("Id" is set to auto increment and is automatically generated by the database server, therefore all newly created rows will initially have 0 before saving).
vm.onEdit = function (e) {
$('input.k-input.k-textbox').blur(function (f) {
//var data = vm.testGrid.dataItem(vm.testGrid.select());
var data = vm.testGrid.dataSource.get(e.model.get("Id")); // will always get the firstly added row
data.set("LookupCol", "1000");
}
});
Is there a better solution to get the row that's been currently edited? Or is there a better way to edit the current row?
The following will give you the data item associated with the current cell:
var dataItem = grid.dataItem(grid.current().closest("tr"));
// You can then set properties as you want.
dataItem.set("field1", "foo");
dataItem.set("field2", "bar");
I used the JQuery closest() function:
vm.onEdit = function (e) {
$('input.k-input.k-textbox').blur(function (f) {
var data = vm.testGrid.dataItem($(e.container).closest("tr"));
data.set("LookupCol", "1000");
}
});
You can also write an extension for the grid, e.g. like this
// extend the grid
kendo.ui.Grid.fn.getCurrentDataItem = function() {
var that = this, current = that.current(), dataItem = null;
if (current) {
dataItem = that.dataItem(current.closest('tr'));
}
return dataItem;
}
JSFiddle example

javascript editable table does not work properly

I am using the following code to make a html table editable (this code is obtained from an online tutorial link: http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425).
$("td").dblclick(function () {
//Obtain and record the value in the cell being edited. This value will be used later
var OriginalContent = $(this).text();
//Addition of class cellEditing the cell in which the user has double-clicked
$(this).addClass("cellEditing");
//Inserting an input in the cell containing the value that was originally on this.
$(this).html("<input type='text' value='" + OriginalContent + "' />");
//directing the focus (cursor) to the input that was just created, so that the user does not need to click on it again.
$(this).children().first().focus();
//the opening and closing function that handles the keypress event of the input.
//A reserved word this refers to the cell that was clicked.
//We use the functions first and children to get the first child element of the cell, ie the input.
$(this).children().first().keypress(function (e) {
//check if the pressed key is the Enter key
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
It seems to work fine. Then I am using the following function to read the contents of the table and create a json representation:
function showRefTable(){
var headers = [];
var objects = [];
var headerRow = $('#dataTable thead tr');
var rows = $('#dataTable tbody tr');
headerRow.find('th').each(function(){
headers.push($(this).text());
});
for (var i=0; i<rows.length; i++){
var row = rows.eq(i);
var object = new Object();
for (var j=0; j<row.find('td').length; j++){
object[headers[j]] = row.find('td').eq(j).text();
}
objects.push(object);
}
var json = JSON.stringify(objects);
alert(json);
}
This function is used as a callback to an onclick event.
The problem is that the function used to read the table contents shows the original contents even if I make an edit (show page source shows the original content).
Thanks
It's really bad to read table contents from .text(). You will not be able to use any formatting for numbers and many other problems. You'd better of keeping table contents in standalone datasourse object and redrawing table from it every time when user changes values.
I would advise using kendo grid - it's powerfull, reliable js table.
EDIT: your function does not work, becuse you said you call it as callback to onclick event. So you read contents of the table before they actually changed.
You should read contents when they are saved. In your case, try calling you function when user saves the input (presses Enter)
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
//Now, when content is changed, call your function
showRefTable();
}

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Categories

Resources