How can I get the text of a JavaScript-generated input element? - javascript

I have a table that creates a row of input elements each time the "+" button is clicked underneath it. All elements are given the className "table-data". Once the "Done" button is clicked I want to loop through all these elements and get the text inside of them:
<table id="myTable"></table>
<button onclick="addRow();">+</button>
<button onclick="getData();">Done</button>
function addRow() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text"></input>';
cell1.className = 'table-data';
cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text"></input>';
cell2.className = 'table-data';
}
function getData() {
inputCells = document.getElementsByClassName("table-data");
for (var i = 0; i < inputCells.length(); i++) {
console.log(inputCells[i].innerHTML);
}
}
However, when I run this code it just logs: 'input type="text"'
I tried using this instead:
console.log(inputCells[i].value);
But this method just logs "undefined". How can I get the value of these input elements?
Note: I don't mind if jQuery is used to answer this question.

I've prepared a solution for you using jQuery as your question is tagged with it. My solution find all inputs in table and then iterates over them using jQuery#each method.
const $table = $('#myTable');
$('#addBtn').on('click', function() {
let tr = $('<tr>');
let td1 = $('<td>');
let td2 = $('<td>');
let input = $('<input>', {
type: 'text',
class: 'table-data'
});
td1.append(input.clone());
td2.append(input.clone());
tr.append(td1);
tr.append(td2);
$table.append(tr);
});
$('#doneBtn').on('click', function() {
$table.find('input').each(function() {
console.log($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable"></table>
<button id='addBtn'>+</button>
<button id='doneBtn'>Done</button>

Details commented in demo
// Reference form
const form = document.forms[0];
/*
//A Pass a number (max 10)
//B Reference table
//C Number of cells in a row
//D if number of cells in a row is less than input number...
//E Run addCols() function
//F Number of cells in a row is equal to number of the input
//G Add row
//H On each iteration...
//I Add a cell
//J Create an input assign type and name
//K Add input to cell.
*/
function addRow(count) {//A
const table = document.querySelector("table");//B
let width = table.rows[0].cells.length;//C
if (width < count) {//D
addCols(table, width, count);//E
width = count;//F
}
const row = table.insertRow();//G
for (let r = 0; r < width; r++) {//H
const cell = row.insertCell();//I
const text = document.createElement('input');//J
text.name = 'data';
text.type = 'text';
cell.appendChild(text);//K
}
return false;
}
// Similar to addRow() but will only adds cells
function addCols(table, width, count) {
let rowCount = table.rows.length;
for (let r = 0; r < rowCount; r++) {
let row = table.rows[r];
for (let c = 0; c < (count - width); c++) {
let cell = row.insertCell();
let text = document.createElement('input');
text.type = 'text';
text.name = 'data';
cell.appendChild(text);
}
}
return false;
}
/*
//A Pass Event Object
//B Prevent the form from sending data to a browser
//C Collect all form controls and convert collection into array
//D Use flatMap() to filter in the inputs with text and extract it
*/
function getData(event) {//A
event.preventDefault();//B
const ui = [...this.elements];//C
let txt = ui.flatMap(field => field.matches('[name=data]') && field.value !== '' ? [field.value] : []);//D
console.log(txt);
return txt;
}
//Register the button to click event
form.elements.add.onclick = function(event) {
const qty = Number(event.target.previousElementSibling.value);
addRow(qty);
};
//Register the form to submit event
form.onsubmit = getData;
input {display:inline-block;font:inherit;width:10vw}
<form>
<input id='qty' type='number' min='0' max='10' value='2'>
<button id='add' type='button'>+</button>
<button type='submit'>Done</button>
<table><tr></tr></table>
</form>

Related

Having trouble creating a combo-box using javascript

I need help creating a combo-box in my js file for the timesheet application? So there is an add row button in the timesheet which will create a new Row. I would like to have a drop-down + input for the first column in the row which will list the customers. Initially, there is no row in the timesheet application user will need to add a row to submit the timesheet. After clicking the add row it will create a row in which I would like to have a drop-down in the "Project Code" section which lists Internal Timesheet Application our customers. The JS code I used to create the table is as follows:
var arrHead = new Array(); // array for header.
arrHead = ['', 'Project Code', 'Project Description', 'Billable Hours'];
// first create TABLE structure with the headers.
function createTable() {
var empTable = document.createElement('table');
empTable.setAttribute('id', 'empTable'); // table id.
var tr = empTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // create table headers
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(empTable); // add the TABLE to the container.
}
//Creating a drop-downlist for Project Code
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else {
// 2nd, 3rd and 4th column, will have textbox.
var ele = document.createElement('input'); //I would like create a combo-box for 2nd Column
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
// delete TABLE row function.
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // button -> td -> tr.
}
// function to extract and submit table data.
function submit() {
var myTab = document.getElementById('empTable');
var arrValues = new Array();
// loop through each row of the table.
for (row = 1; row < myTab.rows.length - 1; row++) {
// loop through each cell in a row.
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
// The final output.
document.getElementById('output').innerHTML = arrValues;
}
//console.log (arrValues); // you can see the array values in your browsers console window. Thanks :-)
Here is the solution to my Problem:
To make a combo-box for only one column
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
**else if (c==1) {**\\ Defining the first column with a drop-down
var values = ["","Tiger", "Dog", "Elephant"];
var select = document.createElement("select");
select.name = "pets";
select.id = "pets";
for (const val of values) {
var option = document.createElement("option");
option.value = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
td.appendChild(select);
}
else{
// 3rd and 4th column, will have textbox.
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}

Why can't I total up these values?

I am building a gradebook web app. I wanted the app to have the ability to calculate grades upon pushing the Final button. However, it's not working for some reason:
var myTable = document.getElementById("myTable");
var r = 0;//how many rows; row index
var c = 1;//how many columns
//make a table
//table must be able to add rows
//table cells should be editable
//save changes?
//
//make a table head row
//all table columns must have a table head
//**
// var firstRow= myTable.insertRow(0);
function addRow(){
//make a new row
var row = myTable.insertRow(r);
//use a while loop to keep creating row cells until you reach last column
var i = 0;
while(i<c){
var cell = row.insertCell(i);
cell.innerHTML ="Students[i]";
i++;
}
r++;
}
function addColumn(){
//make new column
//increment column
var tHead = document.createElement("th");
var allRows= document.getElementsByTagName("tr");//get all rows
//put tHead in first row
allRows[0].append(tHead);
var dateTable = document.createElement("input");
dateTable.type = "date";
tHead.appendChild(dateTable);
//tHead.innerHTML = (c*2);
//add a new cell for each row
var j =1;
while(j<allRows.length){
var row2 = allRows[j];
var cell2 = row2.insertCell(c);
cell2.innerHTML = j;
j++;
}
c++;
f++;
//if there already id a final row, delete it
}
function unEdit(){
//go through every cell
//save input value to a variable
//remove the input cell
var valArray =[];
document.querySelectorAll("td>input").forEach(input => {
var num = parseInt(input.value);
valArray.push(num);
input.remove();
});
//put input value into innerhtml of td
var i = 0;
document.querySelectorAll("td").forEach(td =>{
td.innerHTML=valArray[i];
i++;
});
}
function editTable(){
var allCells = document.getElementsByTagName("td");
for(var k=0; k<allCells.length; k++){
var oldText= allCells[k];
var input = document.createElement("input");
input.type ="number";
input.max = 100;
input.min = 0;
//before making all cells input, save previous innerhtml to var,
//make it into a num instead of a string, and put that value into input
var prev = allCells[k].innerHTML;
prev = parseInt(prev);
input.value = prev;
allCells[k].innerHTML = "";
allCells[k].appendChild(input);
input.onblur;
}
}
function deleteRow(){
document.getElementById("myTable").deleteRow(1);
r--;
}
function deleteColumn(){
//go through each row
//delete cell at each index
var everyRow = document.getElementsByTagName("tr");
for(var p=0; p<everyRow.length; p++){
everyRow[p].deleteCell(-1);
}
c--;
var finalButton = document.getElementById("final");
finalButton.enabled = true;
}
//final grade column
function finalRow(){
//make a <thead>
//make a new cell going down
var finalHead = document.createElement("th");
finalHead.innerHTML= "Final Grade";
var theseRows = document.getElementsByTagName("tr");
theseRows[0].append(finalHead);
for(var t =1; t<theseRows.length; t++){
//go through every cell in the row
//total up the numbers and put it in the final cell
var finalTotal=0;
for(var e =1; e< theseRows[t].length; e++){
var numero = theseRows[t][e].value;
numero = parseInt(numero);
console.log(numero);
finalTotal += numero;
}
//add up the innerhtmls and put it in finalCell
var finalCell = theseRows[t].insertCell(-1);
finalCell.innerHTML = finalTotal;
}
c++;
//disable final button
var finalButton = document.getElementById("final");
finalButton.disabled = true;
var days = document.getElementById("days");
days.disabled = true;
}
addRow();
addColumn();
//make a table head row at the top
//maybe add a print button?
//add a final grade column
//make it so that final row stays final when add new students and days
//do final funtion inside of unEdit() at the end?????
table,td,th{
border: 1px solid black;
border-collapse: collapse;
}
<table id = "myTable"></table>
</script>
<button onclick ="addRow()">Students</button>
<button onclick ="addColumn()" id ="days">Days</button>
<button onclick="editTable()">Edit</button>
<button onclick="unEdit()">Unedit</button>
<button onclick="deleteRow()">Delete Row</button>
<button onclick="deleteColumn()">Delete Column</button>
<button onclick ="finalRow()" id ="final">Final</button>
<button>Print</button>
In the finalRow() function, I can't figure out why the total I keep getting is always 0. Why doesn't it add up the value of the cells? I wanted it to go through every row, get the number values from each cell and total it up. It seems like the issue is with the "numero" variable, but I'm not sure what the issue is.
the first error is because you forgot to declare the variable f, you declared only the variables r and c above.
the second is in the function DeleteRow() there is an indexing error because it finds a negative value when deleting the last row. If you don't even want him to delete the last row, I suggest using a Try-Catch to deal with this error.

Set input to read only?

I am trying to build a grade book web app. I wanted to be able to edit the table cells to input grades, but I can't set it to readonly. What am I doing wrong?
I tried changing the code in the save button, but nothing works. I cant seem to get the input tags for some reason.Am I missing something? Is there another way to try to set the cells to readOnly? I tried getting the td tags, but that didn't work.
var myTable = document.getElementById("myTable");
var r = 0;
var c = 1;
function addRow() {
//insert a row
var row = myTable.insertRow(r);
//insert cells into a row
var cell = row.insertCell(0);
cell.innerHTML = "Students[i]";
r++;
}
function addColumn() {
//add new cell to each row
var allRows = document.getElementsByTagName("tr");
for (var i = 0; i < allRows.length; i++) {
row2 = allRows[i];
cell2 = allRows[i].insertCell(c);
cell2.innerHTML = "Puff";
}
}
function editCell() {
var allCells = document.getElementsByTagName("td");
for (var j = 0; j < allCells.length; j++) {
//clear text, then put in input box
allCells[j].innerHTML = "";
var myInput = document.createElement("input");
myInput.type = "text";
myInput.readOnly = false;
allCells[j].appendChild(myInput);
}
}
function saveData() {
//turn all inputs into readOnly
var allInputs = document.getElementsByTagName("td");
for (var k = 0; k < allInputs.length; k++) {
allInputs[k].id = "inpoot";
document.getElementById("inpoot").readOnly = true;
}
//document.getElementsByTagName("input").readOnly = true;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<table id="myTable"></table>
<button onClick="addRow()">Students</button>
<button onClick="addColumn()">Days</button>
<button onClick="editCell()">Edit</button>
<button onClick="savaData()">Save</button>
HTML IDs must be globally unique within a document. Since you're setting the ID to inpoot for each one, then the getElementById call is always going to be selecting the same element. Also, these elements are the tds, not the inputs themselves.
Try changing your save function thusly:
function saveData(){
//turn all inputs into readOnly
document.querySelectorAll("td > input").forEach(input => {
input.readOnly = true;
});
}
Is there another way to try to set the cells to readOnly?
Use this :
JS :
var myInput = document.createElement("input");
myInput.classList.add("readOnly-input");
CSS :
.readOnly-input{ pointer-events: none; }
The user can't interact when pointer-events are set to none. Let me know if you need more explaination.

How do I check if a cell has a select element in a Javascript loop?

I have a dynamically created table which is generated through a JS addRow function. I would like to loop through this table and check if the cell has a select element in it. If it does then I would like to push the value of the selected option to a dictionary called ingredient_dict.
This is what I have so far:
var table = document.getElementById('selected_ingredients');
var rowCount = table.rows.length;
//table width by counting headers minus the last cell which has a delete button
var cellsCount = table.rows[0].cells.length -1 ;
//loop through all rows (r) in table
for (var r = 1; r < rowCount; r++) {
//initiate dictionary for this ingredient
var ingredient_dict = {};
//loop through each cell (c) in row
for (var c = 0; c < cellsCount; c++) {
var $cell = table.rows[r].cells[c];
if (**CHECK IF CELL HAS A SELECT ELEMENT**) {
$ingredient_dict["UOM"] = $cell.options[$cell.selectedIndex].value
} else if (**CHECK IF CELL HAS INPUT ELEMENT**) {
$ingredient_dict["qty"] = $cell.value
} else {
$ingredient_dict["name"] = $cell.value
}
}
}
I'm not sure if it matters but this is the code in my addRow function to dynamically create the select element:
// ingredient unit of measurement drop down
var cell3= row.insertCell(2);
var unit_of_measure = document.createElement("select");
unit_of_measure.name = "unit_of_measure_select";
cell3.appendChild(unit_of_measure);
I'm pretty new to javascript so I apologize if my code is messy or if this is an obvious question!
var doesCellHaveElement = (cell,element) => {
return cell.innerHTML.toLowercase().indexOf(`<${element}`) >= 0;
};
element would be some name of tag in lowercase. For example:
doesCellHaveElement(cell, "select");
doesCellHaveElement(cell, "input");

How to add an UpperCase function to each textbox in a dynamic table?

I am trying to create a dynamic table with textboxes but I want the textboxes to be converted to upper case every time I write.
Any ideas on how to do this??
Currently this is how I am doing the dynamic table:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
//element.onkeyup = function(){alert()};
cell.appendChild(element);
}
n++;
}
I was trying to do a document.getElementById(element.id).value.toUpperCase() but I am getting an error with a null value for the element.id
Any help is greatly appreciated!
If you're ok with a non JavaScript solution, you could apply this CSS to your inputs:
text-transform: uppercase;
That would make the text uppercase from the beginning...
Darkajax's solution, works, you can target it to inputs within a table with a specific ID
with
#tableid input
{
text-transform: uppercase;
}
I tested your code with the onkeyup function activated:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
cell.appendChild(element);
}
n++;
}
And that worked. However, it uses the last element.id computed for every call to the function... so, when I created one row of 3 cells, every time I typed into a cell, it would alert "102" regardless of which cell I typed in.
This is because the onkeyup function is dynamic. It is called on the keyup action - not set when the object is created. So it uses the element.id value that exists at the time of the action, not what it was when you passed it in the first time. I hope that makes sense.
I had this issue myself on a recent project. One solution is to create a separate function for the inner workings of the for loop as such:
var n = 1;
function createRow (n, i) {
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
return element;
}
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
element = createRow(n, i);
cell.appendChild(element);
}
n++;
}
This code alerts the correct element.id value.
EDIT: you can change the onkeyup() line to read:
element.onkeyup = function(){document.getElementById(element.id).value = document.getElementById(element.id).value.toUpperCase();};
And it should work as you want it to.
with jQuery it will be like
$('.yourClass').val($(this).val().toUpperCase());
or
$('#yourId').css({'text-transform' : 'uppercase'})

Categories