hide show does not work after insertAfter jQuery - javascript

I'm appending some rows to my table and when I click on one row different rows should open, I'm using slideToggle and hide show, but it doesn't work.. the click does work(I added console.log to check)- if I'm writing the rows inside the html it does work.
this is the function:
$('#table').on('click','.good_light_tags_reg',function(){
console.log("hey");
if ($('.good_light_sub_tag_reg').is(":visible")){
$('.good_light_sub_tag_reg').hide();
}
else{
$('.good_light_sub_tag_reg').show();
}
});
the insert part..
var identified_correctly = {};
var rows = "";
for (var i=1 ; i<(table.rows.length -1) ; i++){
if (table.rows[i].className.includes('_tags_reg')){
if (table.rows[i].className != table.rows[i+1].className) {
val = table.rows[i].cells[6].innerHTML;
var pos = val.indexOf("<br>");
var res = parseFloat(val.substring(0, pos));
identified_correctly[table.rows[i].className]=parseFloat(res);
}
}
}
var items = Object.keys(identified_correctly).map(function(key) {
return [key, identified_correctly[key]];
});
items.sort(function(first, second) {
return first[1] - second[1];
});
for (var i=0;i<items.length;i++){
var class_name = items[i][0];
var tags_rows = document.getElementsByClassName(class_name);
var sub_tags_rows = document.getElementsByClassName(class_name.replace("_tags_","_sub_tag_"));
for (var tag=0;tag<tags_rows.length;tag++){
rows += tags_rows[tag].outerHTML;
for (var sub_tag=0;sub_tag<sub_tags_rows;sub_tag++){
rows += sub_tags_rows[sub_tag].outerHTML;
}
}
}
for (var i=0;i<items.length;i++){
$("#table").find("."+items[i][0]).remove();
$("#table").find("."+items[i][0].replace("_tags_","_sub_tag_")).remove();
}
$(rows).insertAfter($(".tag_list_reg").last());

try this using $(document)
$(document).on('click','.good_light_tags_reg',function(){
$('.good_light_sub_tag_reg').toggle();
});
and if the element to show or hide is inside new row, try this
$(document).on('click','.good_light_tags_reg',function(){
$(this).find('.good_light_sub_tag_reg').toggle();
});

Related

Javascript object property returns as undefined only when called from inside another function

I created 3 objects that nest arrays of one another - we'll call them Table, Row and Column so I can show you what's wrong. Table has an array of Rows, and Row has an array of Columns. When I call properties of the Rows from Table, no problem. When I call properties of the Columns from Row, it says undefined, but in the debugger and the console it recognizes the object and it's properties. Maybe I've been staring at it too long but I can't see a fundamental difference.
I stripped the Table layer to be sure it wasn't an issue with nested objects. Here's the code, not working:
function Column()
{
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns)
{
this.columns = [];
this.columns = columns;
this.outputRows = function()
{
var temp = "<tr>";
for(var i = 0; i < this.columns.length; i++)
{
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
console.log("Problem: " + this.columns[i].content);
//yet the object exists, and has the correct properties:
console.log(this.columns[i]);
}
temp += "</tr>";
return temp;
};
}
function test()
{
var col = new Column();
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row([cols]);
console.log(row.outputRows());
}
Here is the interaction between the parent layer and the rows, working fine:
function Table(rows)
{
this.rows = [];
this.rows = rows;
this.outputTable = function()
{
var temp = "<table>";
for(var i = 0; i < this.rows.length; i++)
{
temp += this.rows[i].outputRows();
}
temp += "</table>";
return temp;
};
}
and the updated test function:
function test()
{
var column = new Column();
var cols = [column];
var row = new Row([cols]);
console.log(row.outputRows());
var rs = [row, row];
var table = new Table(rs);
console.log(table.outputTable());
}
Two rows print out as expected this way, with undefined inside each. I originally had column.content written as a function, it doesn't make a difference.
Please tell me what stupid mistake I'm missing here!
Change that line :
var row = new Row([cols])
into
var row = new Row(cols)
since cols is already an array, you don't need to put it in an array again.
function Column() {
this.sampleProp = "testprop";
this.content = "<td>sometext</td>";
}
function Row(columns) {
// removed this.columns = [] since you are assigning it in the next line
this.columns = columns;
this.outputRows = function() {
var temp = "<tr>";
for (var i = 0; i < this.columns.length; i++) {
//this is the line that doesn't work and comes out as undefined:
temp += this.columns[i].content;
}
temp += "</tr>";
return temp;
};
}
function test() {
var col = new Column()
console.log("Printing out the value from here works fine: " + col.content);
var cols = [col];
console.log("It's also fine when it's called from an array: " + cols[0].content);
var row = new Row(cols); // the problem was here
console.log(row.outputRows());
}
test()

How to make a button functional when loaded into a row from local storage in javascript

//loops through all rows and cells and saves them into local storage as objects
window.onbeforeunload = function() {
var rows = document.getElementById('firsttable').tBodies[0].rows;
for (var i = 0; i < rows.length; i += 1) {
localStorage.setItem(i, JSON.stringify({
Item: rows[i].cells[0].innerHTML,
filling1: rows[i].cells[1].innerHTML,
filling2: rows[i].cells[2].innerHTML,
filling3: rows[i].cells[3].innerHTML,
Stock: rows[i].cells[4].innerHTML,
min: rows[i].cells[5].innerHTML,
sold: rows[i].cells[6].innerHTML,
closeAcc: rows[i].cells[7].innerHTML,
sell: rows[i].cells[8].innerHTML,
dltButton: rows[i].cells[9].innerHTML
}));
};
};
//loads the objects into rows with the values in their cells
window.onload = function() {
var r = 0,
c = 0;
//load the actual data from localstorage into html rows
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
};
//where the problem is
$(function() {
$('table td').click(function(e) {
if (e.target.id === "Sellbtn") {
var sell = prompt("Enter the amount");
for (var i = 0; i < table.length; i += 1) {};
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell; //not working and no when put inside the for loop it doesn't work idk why
} else if (e.target.id === "Deletebtn") {
return false;
} else {
var ask = prompt("Input");
$(this).html(ask);
}
});
});
So i insert a row and add the details to the cells and such then as explained in the snippet the first function saves available the rows and cells into a JSON stringified object in the localstorage when the user is closing the browser and then loads them up during onload the problem is with the buttons idk how to make them function after the onload(user closes and opens again). So imagine this you have your HTML table with several rows and their cells and each row has the two buttons(sell and delete) how do i make them function when the user opens up the application again? and btw the buttons are both dynamically added using createElement() when the row is originally added
Try delegating the click event you have on your table rows since they're being created after the DOM loads:
$('table').on("click", "td", function(e) {

Get column value onclick HTML table

I have this html table:
tabela
|A|B|C|D|
_________
001|M|N|O|P|
002|R|S|T|U|
And with this script I can get the row 1st value, e. onclick N get the value 001
var table = document.getElementById("tabela");
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function() {
var rowid = (this.cells[0].innerHTML);
window.location.href = "next.php?rowidphp="+ rowid;
});
}
The thing is that I need to get the column 1st value, e. onclick N shuld get the value B
I'm trying everything but I can reach the point.....
Here's the fiddle: http://jsfiddle.net/t7G6K/
var table = document.getElementById("tabela");
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function (e) {
var rowid = (this.cells[0].innerHTML);
var j = 0;
var td = e.target;
while( (td = td.previousElementSibling) != null )
j++;
alert(rows[0].cells[j].innerHTML);
});
}
Try this:
table = document.getElementById("tablea");
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].cells[2].onclick = function (e) {
rowid = e.target.previousElementSibling.previousElementSibling.textContent;
alert(rowid);
};
}
Here is the Demo
jsFiddle http://jsfiddle.net/2dAkj/9/#
Ok with jQuery i would do it like this.
$(function () {
$('table').on('click', function (e) {
var x = $(e.target);
var index = x.parents('tr').find('td,th').index(x);
alert($(x.parents('table').find('tr').first().find('td,th')[index]).text());
});
});

How to display one row from a HTML table and change to next?

I have a HTML table with 2 columns, 5 rows.
you can do this:
function findMyRow(el)(){
if(!el.parentNode) return null;
else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
tbl.rows[i].onclick = function(e){
var selectedRow = null;
if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
selectedRow = findMyRow(e.target);
//this is just for preventing false event raising
if(!selectedRow) return false;
var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
for(car j=0;j<selectedRow.cells.length;j++){
var cell = selectedRow.cells[j];
//let's say your inputs each has an unique ID based on your columns index
//like <input id="cellData0" ttype="text" />
//or <input id="cellData1" ttype="text" /> and so on
document.getElementById("cellData" + j).value = cell.innerText;
}
}
}
although you can do this more easier than with jQuery.
With Jquery you could do something like:
$(document).ready(function(){
window.rowIndex = 0; // gobal variable
function displayRow(){
var tableRows = $('#mytable tr');
if(tableRows.length <= window.rowIndex) {
window.rowIndex = 0;
}
var rowCells = $(tableRows[window.rowIndex]).find('td');
$('.cellone').val($(rowCells[0]).html());
$('.celltwo').val($(rowCells[1]).html());
window.rowIndex = window.rowIndex + 1;
};
$('.next').click(function(event){ displayRow(); });
displayRow();
});
There is a live demo here Hope it helps!

return or send variable to onchange event

I am trying to achieve the same functionality of a function from two separate events. So the function I created is:
function adding_stuff() {
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates
}
$(".primary .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(".primary .panel-content ul").append(li.concat(names[i]))
}
}
There are two buttons primary and secondary. I want the same functionality for both the functions but the output in different <div>. Currently the selected <div> is ".primary", however I want this to depend on the button which has been clicked.
The function is triggered using:
$("#primary").onchange = adding_stuff;
$("#secondary").onchange = adding_stuff;
NOTE: primary and secondary are inputs of type file.
You can add additional data when you register the callback, which will be made available within the event handler:
$('#primary').on('change', { target: '.primary' }, adding_stuff);
$('#secondary').on('change', { target: '.secondary' }, adding_stuff);
and then within the handler:
function adding_stuff(ev) {
var cls = ev.data.target; // extract the passed data
...
// file handling code omitted
$(".panel-content", cls).append(...)
}
using jquery's change() event
function adding_stuff(obj,objClass) {
var names = [];
var dates = [];
for(var i = 0; i < obj.files.length; i++) {
//adding stuff to names and dates
}
$("."+ objClass+" .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$("."+ objClass+" .panel-content ul").append(li.concat(names[i]))
}
}
$("#primary").change(function(){
adding_stuff(this,'primary');
});
$("#secondary").change(function(){
adding_stuff(this,'secondary');
});
Try
function adding_stuff(opselector) {
return function() {
var names = [];
var dates = [];
for (var i = 0; i < this.files.length; i++) {
// adding stuff to names and dates
}
var ul = $("<ul class='list-unstyled'></ul>").appendTo(opselector)
for (var i in names) {
ul.append("<li>" + li.concat(names[i]) + "</li>")
}
}
}
$("#primary").change(adding_stuff('.primary .panel-content'));
$("#secondary").change(adding_stuff('.secondary .panel-content'));
You can use $(this).attr("class") inside the function. It will return the class of button who triggered the event.
function adding_stuff() {
var div = $(this).attr("class");
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates to $div
}
$(div + " .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(div + " .panel-content ul").append(li.concat(names[i]));
}
}

Categories

Resources