Jquery and clone tables not working - javascript

i have a 2 external jquery files one allows me to clone the last row of a table while the other should allow me to grab the id of select tag based on a class assigned to it. However it only works for the original row and does not work when i clone the rows. Any help would be greatly appreacated.
Js to clone last table row:
$(document).ready(function () {
$("#btn_AddTruck").click(function () {
var $tableBody = $('#tbl_invTruck').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
// Find by attribute 'id'
$trNew.find('[id]').each(function () {
var num = this.id.replace(/\D/g, '');
if (!num) {
num = 0;
}
// Remove numbers by first regexp
this.id = this.id.replace(/\d/g, '')
// increment number
+ (1 + parseInt(num, 10));
});
$trLast.after($trNew);
});
});
Js to get id of select tag by class:
$(document).ready(function()
{
$(function(ready){
$('.selectLp').change(function() {
//alert("working" +this.id);
var Lp_Id = this.id;
alert(Lp_Id);
});
});
})

Since you are creating clone or adding dynamically to DOM you need to change
$('.selectLp').change(function() {
to
$(document).on('change','.selectLp',function(){

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 give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

Filter :nth-child ignoring where css display is none

I have got a script that takes some floating divs in columns of 3 gets the largest height from the 3 columns on 1 row and makes all 3 divs the same height. It then repeats it for each row, the script works fine however I have built a custom filter system in JQuery that makes certain divs hidden or shown depending on the selection of price range, or brand etc.
When I am using the filter it will then remove say column 2 of the top row and make column 4 of the second row move up to the top row. Leaving column 2 in the code and so re-running the height/column check script will not work.
So what I am trying to do is where I am using my filter(':nth-child(3n-2)') add an if statement that will skip all div's that are hidden from the :nth-child selection.
I do understand I can use a function inside my filter(); but its a function that's new to me so am unsure on how to use it exactly.
Here is my working code:
var $sections = $('.section-link');
$sections.filter(':nth-child(3n-2)').each(function () {
var $this = $(this),
$els = $this.nextAll(':lt(2)').addBack();
var sectionheight = new Array();
$els.each(function () {
var value = $(this).find('.section-title').height();
sectionheight.push(value);
});
var newsectionheight = Math.max.apply(Math, sectionheight);
$els.find('.section-title').height(newsectionheight);
})
JSfiddle example
Am trying to use something like this so far:
$sections.filter(function() {
return $(this).css('display') !== 'none';
}, ':nth-child(3n-2)')
Okay managed to get it working by returning the css property before calling the :nth-child
function makeheight(){
var $sections = $('.section-link');
$sections.filter(function() {
return $(this).css('display') == 'block';
}, ':nth-child(3n-2)').each(function () {
var $this = $(this),
$els = $this.nextAll(':lt(2)').addBack();
var sectionheight = new Array();
$els.each(function () {
var value = $(this).find('.section-title').height();
sectionheight.push(value);
});
var newsectionheight = Math.max.apply(Math, sectionheight);
$els.find('.section-title').height(newsectionheight);
});
}

Styling table according to its contents

I have the following table: http://jsfiddle.net/UfhVc/1/
I am trying to:
Get the same style on all rows who have the same ID
Highlight the differences in each on the rows with the same ID.
But right now I can't seem to figure out the logic needed for step 1). It's ok to use jQuery, I just found it easier to use plain js.
Also, I get a warning in this part of the code:
table.rows[i+1].cells[0].innerHTML
Like this?
var newColor = "#F1D0F2";
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () { //Loop through the trs leaving out the header
var txt = $(this).find('td:eq(0)').text(); //get the text of the id column
var $this = $(this);
var matchingRows = $('#tbl tr').not(this).filter(function () { //get the matching rows whose id colum value is same
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', newColor); //apply css for match
matchingRows.find('td').css('background-color', function (i) { //apply background color
if ($this.find('td:eq(' + i + ')').text() != this.innerHTML) return diffColor; // to the tds of matching rows but column valud differ.
});
});
Fiddle
References:
:gt()
filter()
css()
:eq()
Edit
Based on your comment here is the update:
var allColors = ["#333333","#990099", "#1295A6", "#FFFF99"]; //Set up the colors in to an array
var diffColor = "#CECECE";
$('#tbl tr:gt(0)').each(function () {
var txt = $(this).find('td:eq(0)').text();
var $this = $(this);
if($this.is('.transformed')) //check for class transformed is present if so this has already been processed skip it.
return;
//Get the matching rows whose id column value is same
var matchingRows = $('#tbl tr').filter(function () {
return $(this).find('td:eq(0)').text() == txt;
}).css('background-color', allColors.shift()).addClass('transformed'); //Set the color and add a class to avoid latter processing
matchingRows.find('td').css('background-color', function (i) { //apply background color
var $parTd = $this.find('td:eq(' + $(this).index() + ')');
if ($.trim($parTd.text()) != $.trim(this.innerHTML)) // to the tds of matching rows but column value differ.
{
$parTd.css('background-color', diffColor);
return diffColor;
}
});
});
Fiddle
For step one:
There are a few ways you can do it, I would probably attach a class to all table cells which are of a certain type, so you can easily select them all at once for editing.
<table>
<tr>
<td class="id-cell"></td>
</tr>
</table>
Then you could simply query it with CSS like:
.id-cell {
background-color:red;
}
But you can also just use more jQuery / JavaScript to find those table cells you're looking for anyways. This fiddle uses jQuery to find all the cells which are in the "id" column, and paint the background red.
http://jsfiddle.net/8QL22/
Another way of doing it:
$("table tr:not(:first-child) td:first-child").each(function(index) {
var thisId = $(this);
$("table tr:not(:first-child) td:first-child").each(function(_index) {
if (index != _index && thisId.text() == $(this).text())
{
thisId.parent("tr").css("backgroundColor", "red");
$(this).css("backgroundColor", "red");
$(this).siblings("td").each(function(sindex) {
var other = $(thisId.siblings()[sindex]);
if (other.text() != $(this).text())
other.css("backgroundColor", "yellow");
});
}
});
});
http://jsfiddle.net/w4mvp/

Why can't I bind this onclick event?

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.

Categories

Resources