Dynamically created buttons within cells of a dynamically created table - javascript

I am trying to make a color swatch that can be used to select colors from. My thought is to create a table, and have each cell of the table be a button from which the user can click to select the color they want to use. Th this point I have not even tried to give my buttons any functionality until I can actually determine that they are generating I am simply trying to lay out the table at this point and test whether or not the buttons are appending to each cell. This is the reason for the innerHTML = 'test'. However nothing is appearing so I fear the buttons are not properly appending. I am brand new to coding and would prefer to stick with vanilla JS for the time being. Mahalo
// get reference for the pixelPainter div
let body = document.getElementById('pixelPainter');
//create the color swatch
let swatch = document.createElement('table');
swatch.id = 'swatch_base';
for (var i = 0; i<6; i++){
let row = document.createElement('tr');
//create columns and attach buttons to each cell so that the buttons can be selected to choose a color
for (var i = 0; i<10; i++){
let cell = document.createElement('td');
let colorButton = document.createElement('button');
colorButton.className('colorChoice');
colorButton.innerHTML('test'); // just trying to test for button
cell.appendChild(colorButton);
row.appendChild(cell);
}
swatch.appendChild(row);
}
body.appendChild(swatch);
swatch.setAttribute('border', '1');

try this https://jsfiddle.net/qnrra88L/
actually, className and innerHTML are not a functions, also className should be classNames
change these two lines
colorButton.className('colorChoice');
colorButton.innerHTML('test');
as
colorButton.classNames = 'colorChoice';
colorButton.innerHTML = 'test';

Related

Unable to access the class inside dynamically created table

I've created a table using js. I've given class names for few cells. I want to access these cells later on and remove the class name. But I'm unable to do it. This is how I create the table dynamically:
for (var j = 0; j < TotalNumOfPlayers; j++)
{
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (header)
{
var cellText = document.createTextNode(nameOfPlayers[j]);
}
else
{
var cellText = document.createTextNode(oldScore[j]);
cell.setAttribute("class", "lastrow");
}
cell.appendChild(cellText);
row.appendChild(cell);
}
Here is how I tried to access the cells and remove the classes:
document.querySelectorAll(".lastrow").classList.remove("lastrow");
It throws the following error:
Cannot read property 'remove' of undefined
at :1:48
I vaguely understand that it is looking at the parent level and sees no class attached but it should be looking inside the td. Did I get it right? If yes, how should I accomplish this?
You should remove class from all elements in loop
let lastrows = document.querySelectorAll('.lastrow');
for (let i=lastrows.length;i--;){
lastrows[i].classList.remove('lastrow');
}

How to access rows in table generated in javascript

I've generated a table in my html by using this code:
var board=document.getElementById("tab");
for(var i=0; i<lvl1.rows; i++ )
{
var row=board.insertRow();
for(var j=0; j<lvl1.cols; j++)
{
var cell = row.insertCell();
}
}
The point is to keep the design of the page almost totally separated from the game engine (creating a Minesweeper game).
Imagine I want to change the colour of the cell in position [2][3]. How can I change the background colour of this cell if I don't have the "td's" and "tr's" in the HTML code?
Thanks
To access the ith cell of row j, use:
board.rows[j].cells[i]
You can set the background color style of a cell like this.
board.rows[j].cells[i].style.backgroundColor = "red";

Two functions don't work together, but no errors

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.

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.

Tigra Calendar and Javascript DOM - How do I attach?

Fine, my question is as follows. I am adding rows to a table dynamically using the DOM, and everything goes really well. However, in one of the cells I need to add this calendar: http://www.softcomplex.com/products/tigra_calendar/
When I execute the code to add the calendar, it will create it wherever I place it and mess with everything. What I want to do, is to attach that calendar to the cell and that it executes whenever the nodes enter to the table. This is the code:
function addpago()
{
var i = 0;
//Create a select
var cuota=document.createElement('select');
cuota.name="cuota"+cantpagos;
cuota.id="cuota"+cantpagos;
for(i=1;i<=11;i++)
{
cuota.options[i-1]=new Option("Cuota "+i, i);
}
//Create an input and add an event, this code works correctly
var monto=document.createElement('input');
monto.type='text';
monto.name=monto.id='monto'+cantpagos;
if(monto.addEventListener)
monto.addEventListener("blur", sumpagos, false);
else if(monto.attachEvent)
monto.attachEvent("onblur", sumpagos);
else
monto.onblur = sumpagos;
monto.size=6;
//Create an input
var ncheque = document.createElement('input');
ncheque.type='text';
ncheque.name=ncheque.id='cheque'+cantpagos;
ncheque.size=10;
//Create a select
var bancos = document.createElement('select');
bancos.name=bancos.id='banco'+cantpagos;
bancos.options[0]=new Option("BANCO DE CHILE",1);
bancos.options[1]=new Option("BANCOESTADO",2);
bancos.options[2]=new Option("BANCO DE CRÉDITO E INVERSIONES",3);
bancos.options[3]=new Option("BANCO SANTANDER",4);
bancos.options[4]=new Option("BANCO ITAÚ",5);
//Create an input
var plaza = document.createElement('input');
plaza.type='text';
plaza.name=plaza.id='cheque'+cantpagos;
plaza.size=6;
//Create an input
var fecha = document.createElement('input');
fecha.type='text';
fecha.name=fecha.id='fecha'+cantpagos;
fecha.readOnly=true;
fecha.size=14;
//Create a tr, add several td's and attach each element created before to the child td's
row = document.createElement('tr');
cell = document.createElement('td');
cell.appendChild(cuota);
row.appendChild(cell);
cell = document.createElement('td');
cell.appendChild(monto);
row.appendChild(cell);
cell = document.createElement('td');
cell.appendChild(ncheque);
row.appendChild(cell);
cell = document.createElement('td');
cell.appendChild(bancos);
row.appendChild(cell);
cell = document.createElement('td');
cell.appendChild(plaza);
row.appendChild(cell);
cell = document.createElement('td');
cell.appendChild(fecha);
//I need to add the calendar at this point, but I can't figure out how
cell.appendChild(new tcal ({'formname': 'ingpagos', 'controlname': 'fecha'+cantpagos, 'imgpath': 'www.codesin.cl/Tigra/img/'}));
row.appendChild(cell);
document.getElementById('tabpagos').appendChild(row);
cantpagos++; //Global variable being updated
document.getElementById('cantpagos').value=cantpagos;
}
What should I do? Thanks beforehand...
I've used Tigra Calendar before. Why are you adding it as a node? It's an object you just instantiate, the program takes care of modifying the DOM etc. =)
You do however need to wait to instantiate it until after the input field is IN the DOM =)
...
row.appendChild(cell);
document.getElementById('tabpagos').appendChild(row);
new tcal ({'formname': 'ingpagos', 'controlname': 'fecha'+cantpagos, 'imgpath': 'www.codesin.cl/Tigra/img/'})
Though that imgpath looks suspect so you may need to play with it some =)

Categories