Two functions don't work together, but no errors - javascript

I have a couple of javascript functions which:
show/hide some table rows
add a new row
Both work on the same page, but not under specific circumstances.
Here's the fiddle of the code below:
/*************** show/hide sections ***************/
$('.arrow').click(function(event) {
var sec_id = $(this).attr('id').split('.')[0]; // admin.link -> admin
if ($(this).closest('td').attr('class') == 'subtitle')
$('.s_'+sec_id).toggle(); // toggle hide/show for 1 item (section)
else
$(this).closest('tr').nextUntil('tr:not(.s_' + sec_id+')').toggle();
});
/*************** Add rows ***************/
$('.add_row').click(function(event) {
var sid = $(this).attr('sid'); // the id of the <tbody>
var tbody = document.getElementById(sid); // the <tbody> to add rows to
// === GENERATE NEW NAMES for inputs
// get the name of the first input in the last row
var rows = tbody.rows;
var rowinput = rows[rows.length-1].getElementsByTagName('INPUT');
// split name into array
var name_piece = rowinput[0].name.split('][');
// create name for next row; check if last row is a blank row
var reg = new RegExp('^[0-9]+$');
if (reg.test(name_piece[1])) // if integer
var iteration = parseInt(name_piece[1], 10) + 1; // convert to int with base 10
else
iteration = 1;
if (iteration < 10)
iteration = '0'+iteration; // add left padding to ensure sort order
var front = 'items['+sid.substring(2)+']['+iteration+']'; // front of input name (remove the 's_' from name)
// END GENERATE NEW NAMES for inputs
// === CREATE ROW
var row = document.createElement('tr'); // create a row
var td1 = document.createElement('td'); // create first cell
td1.setAttribute('colSpan', 2);
td1.innerHTML = '<input type="text" name="'+front+'[desc]" maxlength="100" />';
var td2 = document.createElement('td'); // create second cell
td2.innerHTML = '<input type="text" name="'+front+'[price]" maxlength="9" onChange="calc_ttl()" class="right small" />';
var td3 = document.createElement('td'); // create third cell
td3.setAttribute('colSpan', 3);
// END CREATE ROW
// output
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
tbody.appendChild(row);
});
In the fiddle, you'll see 3 links, all of which work as they should. The only exception is if I add a row while the hidden rows are shown; eg.:
Click "Subsection" to show rows
Click "Add row"
Click "Subsection" to hide rows <-- Fails here
From then on, the "Subsection" link no longer works unless I reload the page. The code checks out, and Firebug reports no errors, so I'm at a loss. Any advice much appreciated.

The problem is not in the jQuery code you've posted here. It is in the HTML. In your fiddle you have:
<tr onMouseOver="this.className='highlight'" onMouseOut="this.className='normal'" class="s_grp_2d_ttl_asset" style="display: none;">
Once the row is visible, as soon as the mouse moves over it, the s_grp_2d_ttl_asset class is replaced by the highlight class, which makes your click event stop at the first element. If you used the addClass, removeClass, or toggleClass functions instead, you could make the change without completely removing the original class.

Related

Finding cell value of dynamically generated table row

I am trying to delete an array record based on what table row is clicked.
This function adds a button to a row and appends it to the end of the table
function addButtons(table, tr){
var delBtn = document.createElement("button");
delBtn.innerHTML = "×"
delBtn.onclick = deleteBu(tr)
tr.appendChild(delBtn);
table.children[1].appendChild(tr)
}
The function below is meant to delete an array record based on the row clicked. For example, in row 1, the first cell is "45". Based on this, the record is deleted if it is found in the array storageProblem.
Here is what I have so far. The issue is because I am using tr as the action listener, so simply clicking on the row will delete the row, it is not localized to the button. But using tr is the only way I have found to get the first td of a row.
function deleteBu(tr){
$(tr).click(function(){
var value=$(this).find('td:first').html();
for(i = 0; i < storageProblem.length; i++){
if(value == storageProblem[i][0]){
storageProblem.splice(i, 14)
loadCallProblemTable()
}
}
})
}
I'm not sure if I've understood your question right but maybe try this solution:
function deleteBu(x) {
var Index = $(x).closest('tr').index();
console.log("Row index: " + Index);
}

Javascript - Listener executing on assignment

So, I'm currently working on a HTML page that displays a table with an editable text box and a delete button for the row for every quote in a list. The list is fetched from a stored file, so I need to dynamically generate this table and its rows every time I fetch it. However, when this code runs, the table generated is empty, because when the listener is added, the delete row function executes and just removes the row right after it's added.
for (var i = 0; i < quotesArray.length; i++) {
//Insert a new row into the table.
var newQuoteRow = quoteList.insertRow(-1);
var cellOne = newQuoteRow.insertCell(0);
var cellTwo = newQuoteRow.insertCell(1);
//Insert editable text boxes for a quote into the row.
var quoteInput = document.createElement('input');
quoteInput.value = quotesArray[i];
quoteInput.className = "quote";
cellOne.appendChild(quoteInput);
//Put a delete button at the end of the row.
var deleteQuoteButton = document.createElement('button');
deleteQuoteButton.innerHTML = "x";
cellTwo.appendChild(deleteQuoteButton);
deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow(deleteQuoteButton));
}
});
}
function deleteCurrentQuoteRow(buttonToDelete) {
var currentRow = buttonToDelete.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}
From what I understand, this problem occurs because the function linked to in the addEventListener method has a parameter, which causes it to execute immediately instead of waiting for a click. However, I can't think of a way to implement this without passing the button being clicked as the parameter, because then I won't know which row to delete. How can I fix this so that the table will actually populate, and the delete button will actually delete a row?
Currently you are invoking the function deleteCurrentQuoteRow and assigning its return value which is undefined as event listener.
Use
deleteQuoteButton.addEventListener('click', function(){
deleteCurrentQuoteRow(this); //Here this refers to element which invoke the event
});
OR, You can modify the function deleteCurrentQuoteRow as
function deleteCurrentQuoteRow() {
var currentRow = this.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}
Then you can just pass the function reference as
deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow);

How can I reference an element after I have appended it using javascript not jquery

I am doing some basic javascripting and am creating a 3 column table created by javascript sourced from an xml. The table is created by appending all the data in rows via javascript.
The first column has an input checkbox, created via javascript, that if ticked fetches a price from the third column on that row and adds all the prices of the rows selected to give a price total.
The problem I am having is I don't seem to be able to reference the appended information to obtain the information in the related price column (third column).
I have attached both the function I am using to create the table which is working and the function I am using to try and add it up which isnt working.
I found the following two articles Getting access to a jquery element that was just appended to the DOM and How do I refer to an appended item in jQuery? but I am using only javascript not jquery and would like a javascript only solution if possible.
Can you help? - its just the calculateBill function that isn't working as expected.
Thank you in advance
function addSection() {
var section = xmlDoc.getElementsByTagName("section");
for (i=0; i < section.length; i++) {
var sectionName = section[i].getAttribute("name");
var td = document.createElement("td");
td.setAttribute("colspan", "3");
td.setAttribute("class","level");
td.appendChild(document.createTextNode(sectionName));
var tr = document.createElement("tr");
tr.appendChild(td);
tbody.appendChild(tr);
var server = section.item(i).getElementsByTagName("server");
for (j=0; j < server.length; j++) {
var createTR = document.createElement("tr");
var createTD = document.createElement("td");
var createInput = document.createElement("input");
createInput.setAttribute("type", "checkbox");
createInput.setAttribute("id", "checkInput");
createTD.appendChild(createInput);
createTR.appendChild(createTD);
var item = server[j].getElementsByTagName("item")[0].innerHTML;
var createTD2 = document.createElement("td");
var createText = document.createTextNode(item);
createTD2.appendChild(createText);
createTR.appendChild(createTD2);
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
}
}
}
onload = addSection();
function calculateBill() {
var finalBill = 0.0;
var checkBox = document.getElementById("checkInput");
for (i=0; i < checkBox.length; i++) {
if (checkBox[i].checked) {
var parentTR = checkBox[i].parentNode;
var priceTD = parentTR.getElementsByTagName('td')[2];
finalBill += parseFloat(priceTD.firstChild.data);
}
}
return Math.round(finalBill*100.0)/100.0;
}
var button = document.getElementById("button");
button.onClick=document.forms[0].textTotal.value=calculateBill();
When you do x.appendChild(y), y is the DOM node that you are appending. You can reference it via javascript either before or after appending it. You don't have to find it again if you just hang on to the DOM reference.
So, in this piece of code:
var createInput = document.createElement("input");
createInput.setAttribute("type", "checkbox");
createInput.setAttribute("id", "checkInput");
createTD.appendChild(createInput);
createInput is the input element. You can reference it with javascript at any time, either before or after you've inserted it in the DOM.
In this piece of code:
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
You're creating a <td> element and putting a price into it. createTD3 is that particular <td> element.
If you want to be able to find that element sometime in the future long after the block of code has run, then I'd suggest you give it an identifying id or class name such that you can use some sort of DOM query to find it again. For example, you could put a class name on it "price" and then be able to find it again later:
var price = server[j].getElementsByTagName("price")[0].innerHTML;
var createTD3 = document.createElement("td");
createTD3.className = "price";
var createText2 = document.createTextNode("£" + price);
createTD3.appendChild(createText2);
createTR.appendChild(createTD3);
tbody.appendChild(createTR);
Then, you could find all the price elements again with:
tbody.querySelectorAll(".price");
Assuming tbody is the table where you put all these elements (since that's what you're using in your enclosed code). If the table itself had an id on it like id="mainData", then you could simply use
document.querySelectorAll("#mainData .price")
to get all the price elements.
FYI, here's a handy function that goes up the DOM tree starting from any node and finds the first node that is of a particular tag type:
function findParent(node, tag) {
tag = tag.upperCase();
while (node && node.tagName !== tag) {
node = node.parentNode;
}
return node;
}
// example usage:
var row, priceElement, price;
var checkboxes = document.querySelectorAll(".checkInput");
for (var i = 0; i < checkboxes.length; i++) {
// go up to the parent chain to find out row
row = findParent(checkboxes[i], "tr");
// look in this row for the price
priceElement = row.querySelectorAll(".price")[0];
// parse the price out of the price element
price = parseFloat(priceElement.innerHTML.replace(/^[^\d\.]+/, ""));
// do something here with the price
}

How to permute 2 cells of a table

I'd like to do a small function that would permute 2 cells of a table with jQuery (or PHP/Ajax).
Let's say I have the following table:
<table class="table">
<tr>
<td class="btn" data-cellN="1">
01
</td>
<td class="btn" data-cellN="2">
02
</td>
</tr>
<tr>
<td class="btn" data-cellN="3">
05
</td>
<td class="btn" data-cellN="4">
06
</td>
</tr>
</table>
How to select 2 cells and permute them?
EDIT:
I made my way through the function thanks to your advice, nevertheless. It is working the first time bug I got a weird bug coming from the c1 c2 c3 variables, I don't know why,
could anyone help me to finish my function please?
Here is my Javascript: (it is wrapped in a doc ready)
var nbbuttonclicked=0; // to trigger the movecell function after the second button was clicked
var count=0; //Number of tinme we moved a cell
var table = {
c1:null,
c2:null,
c3:null,
check: function(){
$('td').on('click', function(){ //When the user click on a button we verify if he already clicked on this button
if( $(this).hasClass('btn-info') ) {
//If yes, then remove the class and variable c1
$(this).removeClass('btn-info');
table.c1=0;
nbbuttonclicked--;
}else{
//if no, then add a class to show him it is clicked and remember the value of the cell
$(this).addClass('btn-info');
if( typeof table.c1 === 'undefined' || table.c1===null) {
table.c1 = $(this);
console.log('c1:'+table.c1.html());
}else{
table.c2 = $(this);
console.log('c2:'+table.c2.html());
}
nbbuttonclicked++;
if( nbbuttonclicked==2 ) {
table.movecell(table.c1,table.c2); // we trigger the function to permute the values
}
}
});
},
movecell: function(c1, c2){
//We reset that variable for the next move
nbbuttonclicked=0;
//we move the cells
table.c3=c1.html();
c1.html(c2.html());
c2.html(table.c3)
c1.removeClass('btn-info');
c2.removeClass('btn-info');
table.c1=table.c2=table.c3=c1=c2=null;
},
// movecell: function(c1, c2){
// We check if the cells.html() are = to data-cellN. If yes, you won
// foreach()
// },
// var row = $('table tr:nth-child(1)')[0];
// moveCell(row, 0, 3);
};
table.check();
and here is a sample:
http://jsbin.com/exesof/2/edit
Try this code:
var cell0,
cell1,
next,
row0,
row1;
$('td').on('click', function() {
if(!cell0) {
cell0 = this;
row0 = cell0.parentNode;
return;
} else if(!cell1) {
cell1 = this;
row1 = cell1.parentNode;
// === Switch cells ===
next = cell0.nextSibling;
row1.insertBefore(cell0, cell1);
row0.insertBefore(cell1, next);
// ====================
row0 = row1 = cell0 = cell1 = next = null;
}
});
Working example you can try here: http://jsbin.com/irapeb/3/edit
Click one of the cells, than another one and see they are switched :)
This code will move the 4th td (referenced as cell[3]) on place of the first cell (cell[0]) in the first row (and the 1st becomes the 4th):
function moveCell(row, c1, c2) {
var cell = row.cells;
arr = [c1, c2].sort(),
c1 = arr[1],
c2 = arr[0];
row.insertBefore(row.insertBefore(cell[c1], cell[c2]).nextSibling, cell[c1].nextSibling);
}
var row = $('table tr:nth-child(1)')[0];
moveCell(row, 0, 3);
http://jsfiddle.net/2N2rS/3/
I wrote this function to simplify process. It uses native table methods.
Modifying the number of row (:nth-child(1)) and indexes of the table cells you can permute them as you need.
with jQuery, you can do it with:
$(document).ready(function() {
$("table.table tbody tr td:first-child").each(function(index, element) {
// this and element is the same
$(this).insertAfter($(this).next());
});
});
Assuming you don't ommited the tbody element (which is automatically added by some browser as default behaviour)
working example
If you want to do the process when clicking on the first cell, you just have to use on with click event instead of each.
$(document).ready(function() {
$("table.table tbody tr td:first-child").on('click', function(clickEvent) {
$(this).insertAfter($(this).next());
});
});
This can be done in pure javascript:
Fetch clicked sell count;
Fetch data of both cells, when they are selected;
Replace cell values with the opposite ones;
Store new values in DB via ajax call.
Now it's up to you to write the script.

How to tell if a row contains cells with textbox with javascript

I have a table that is built dynamically from a user specified query to a database and I want to give the user the option to edit the data from the generated HTML table. When the user double clicks on the row containing the data they want to edit, I have a new row appear underneath it with textboxes for them to submit new values. Right now, when the user clicks double clicks two rows, both rows of textboxes remain in the table and I want to delete the first row before the second shows up. My question is, what is a good was to find table rows containing textboxes so that I can perhaps use JavaScript's deleteRow() function?
I'm generating rows like so:
function editRow(row) {
var table = document.getElementById("data");
var newRow = table.insertRow(row.rowIndex + 1);
var cell;
for (var i = 0; i < row.childNodes.length; i++) {
cell = newRow.insertCell(i);
textBox = document.createElement("input");
textBox.type = "text";
textBox.placeholder = row.childNodes[i].innerHTML;
textBox.style.textAlign = "center";
textBox.style.width = "90%";
cell.appendChild(textBox);
}
}
and the only way I can I can think of doing it is something like (pseudo code):
for all table rows
if row.childNodes.innerHTML contains 'input'
deleteRow(index)
Thanks for the help
You could use jQuery. Assuming row is a DOM element, this should work:
var textBoxes = $("input:text", row);
i guess the easiest option would be to add the created rows to an array. This way you simply have to delete the rows inside the array and not iterate through the whole table.
I ended up doing the following:
function editRow(row) {
var table = document.getElementById("data");
clearExistingTextBoxes(table);
...
}
function clearExistingTextBoxes(table) {
var tBoxRow = table.getElementsByTagName("input");
if (tBoxRow.length > 0) {
tBoxRow = tBoxRow[0].parentNode.parentNode;
table.deleteRow(tBoxRow.rowIndex);
}
}
Assuming I'm only going to be clearing one row at a time.

Categories