How can I inspect if an element inside a cell is checked? - javascript

The function "insert()" makes table cells that contain task names given by input. Every task name has a checkbox appended and how can I inspect if an element in a cell is checked so I can change its properties? I want the function "completeTasks()" to check for a checked element so when I press the button that calls the function, elements that are checked should be green and strikethrough(line-through).
<html>
<head>
</head>
<body>
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
// if one or more elements are checked when clicking this button
// then the checked task name(s) would have green color and have a line-through text decoration.
//.style.color = "green";
//.style.textDecoration = "line-through";
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>
</body>
</html>

You can first target all the checked check box using Document.querySelectorAll(), then loop through them and set the style to the closest td element.
Demo:
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
var checkedEl = document.querySelectorAll('#tabl3 input:checked'); // get all the checked checkbox inside the table
checkedEl.forEach(function(el){ //loop through them
el.closest('td').style.color = "green";
el.closest('td').style.textDecoration = "line-through";
});
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>

Related

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.

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

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>

Get selected row value using javascript

I have dynamically add the table on html button click. Add the teamname,teamid,radio button.
HTML attributes:
<input type="button" value="Generate a table." onclick="generate_table()">
Javascript function :
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
4 rows with 3 columns will generate on the button click , Now i need to get the details on the radio button click.
If i select the radio button from the first row i need to show the teamid in alert box? how can I achieve this in javascript?
try this code below should alert teamid cell's innerText
<input type="button" value="Generate a table." onclick="generate_table()">
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
//here we set value of radio button based on element index and we set a classname for teamid cell
radio.setAttribute("value", i);
cell1.setAttribute("class", "selected_teamid");
//here we add click event
radio.setAttribute("onclick", "getteamid("+i+")");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
function getteamid(i){
alert(document.getElementsByClassName("selected_teamid")[i].innerText);
}
<input type="button" value="Generate a table." onclick="generate_table()">
just add this line, before appending the radio element:
radio.onclick = function(){alert(this.value};
You just need to add an event handler to the radio button when you create it:
...
radio.addEventListener('click', radioButtonClick, false);
...
function radioButtonClick() {
alert(this.getAttribute('value'));
}
This requires that you set the value of the radio button to your team id, or store it on the radio button (which will be the this inside the event handler) in some other way.
You aren't passing a teamid anywhere, so I assumed the teamid is the index of the looped array.
var generate_table = function()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
radio.setAttribute('data-team', i); // passing the team id
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
// add an event listener on a dynamic element, and alert the team id
document.addEventListener('click', function(e) {
if(e.target && e.target.hasAttribute('data-team')) {
alert(e.target.getAttribute('data-team'));
}
});
You have several way to achieve that:
The easiest way I think is to add an attribute 'teamid' to the radio button. Then just listen for click event and get this value back.
radio.setAttribute('teamid', teamid);
radio.addEventListener('click', onRadioClick);
function onRadioClick(domEvent){
console.log(domEvent.target.getAttribute('teamid'));
}
For me it is not the best way because you need to put some information in the DOM... In my opinion, it would be better to separate the presentation and the data :
var tableData = [
{teamId: 'someId0', title:'title0', someData:'...' },
{teamId: 'someId1', title:'title1', someData:'...' },
{teamId: 'someId2', title:'title2', someData:'...' }
];
for (var i = 0, n = tableData.length ; i < n ; i++){
var rowData = tableData[i];
// Create the row using rowData
// ...
radio.setAttribute('teamid', rowData.teamId);
radio.addEventListener('click', onRadioClick.bind(rowData));
// ...
}
function onRadioClick(domEvent){
// Here this represent data of the row clicked
console.log(this.teamId);
}
I think it's easier to manage because every data are JS side... You don't store any data in the DOM... However both works ;) Hope it helps
radio.setAttribute("onclick", "anotherFunction(this)")
and after this function create anotherFunction():
function anotherFunction(object){
alert(object.parentNode.parentNode.firstChild.innerHTML);
}

Taking data from the form and put it in the table row by using JavaScript.

I have created form. now I need to take input data into table. So I have created the code but it does not working. In here, I take the input-data by using id = "input1" then I click on the submit button and it will call for myfunction() function. That function will show the data in the table. But it not working.
<html>
<head>
<title>
</title>
</head>
<body>
<div id="form1">
</div>
<div id="table1">
</div>
<script>
var f = document.createElement("form");
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',"input1");
i.setAttribute('id',"input1");
var s = document.createElement("input");
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
s.setAttribute('id',"done")
f.appendChild(i);
f.appendChild(s);
document.getElementById("form1").appendChild(f);
</script>
<script>
document.getElementById("done").onclick = function() {myFunction()};
function myFunction() {
var t = document.createElement("table");
t.setAttribute('border',"1");
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.getElementById("input1");
cell.appendChild(cellText);
row.appendChild(cell);
t.appendChild(row);
document.getElementById("table1").appendChild(t);
}
</script>
</body>
</html>
You need to update your code to following
document.getElementById("done").onclick = function() {
event.preventDefault();
myFunction()
};
For reference - http://plnkr.co/edit/ZgMWu6tCb95R9TEAQKbi?p=preview
var s = document.createElement("input");
s.setAttribute('type',"button");
s.setAttribute('value',"Submit");
s.setAttribute('id',"done");
Change input type to button, as you are showing the data in a table you dont need submit button, if you are giving submit button it will automatically try to call the action which is not defined. If you want o use submit then add event.preventDefault(); to the myFunction()
You should change the type of button from submit to button.
Also if you just need the text inside the input box take the value instead of the element.
<html>
<head>
<title>
</title>
</head>
<body>
<div id="form1">
</div>
<div id="table1">
<table id="myTable" border="1"></table>
</div>
<script>
var f = document.createElement("form");
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',"input1");
i.setAttribute('id',"input1");
var s = document.createElement("input");
s.setAttribute('type',"button");
s.setAttribute('value',"Submit");
s.setAttribute('id',"done")
f.appendChild(i);
f.appendChild(s);
document.getElementById("form1").appendChild(f);
</script>
<script>
document.getElementById("done").onclick = function() {myFunction()};
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cellText = document.getElementById("input1").value;
cell1.innerHTML = cellText;
}
</script>
</body>
</html>
Try this,
You should consider a decent framework such as jQuery / Angular / ... to do these HTML manipulations
I've changed the form input type="submit" to button type="button", added .value to the cellText var, used .innerHTML to set it inside the <td>
Online Demo - https://plnkr.co/edit/ApNX7vuN31Wu0fbCR9Vh?p=preview
<script>
var f = document.createElement("form");
var i = document.createElement("input");
i.setAttribute('type', "text");
i.setAttribute('name', "input1");
i.setAttribute('id', "input1");
var s = document.createElement("button");
s.setAttribute('type', "button");
s.innerHTML = "Click me";
s.setAttribute('id', "done")
f.appendChild(i);
f.appendChild(s);
document.getElementById("form1").appendChild(f);
</script>
<script>
document.getElementById("done").onclick = function() {
myFunction()
};
function myFunction() {
var t = document.createElement("table");
t.setAttribute('border', "1");
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.getElementById("input1").value;
cell.innerHTML = cellText;
row.appendChild(cell);
t.appendChild(row);
document.getElementById("table1").appendChild(t);
}
</script>

How to specify column to add cell to

So I have a table with one row and two columns that creates new rows with info input by the user.
I want to know how to add info into the second column of cells.
The following code adds cells to the first column only:
<!DOCTYPE HTML>
<html>
<body>
Something must be entered here:
<input id="inputName" style="width:100px;"></input>
<button onclick="addRowCell('table1')">Add row</button>
<table id="table1" style="border:1px solid black;">
<tr id="myRow1">
<td>ID</td>
<td>Content 1</td>
</tr>
</table>
<script>
i=1;
function addRowCell(el){
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
x.innerHTML=fName;
i++;
}
</script>
</body>
</html>
JSFiddle for the above: http://jsfiddle.net/tC2zG/
Edit: for anyone with a similar problem - what you see here isn't cells being added, it's rows being added.
You're not adding cells at all, just rows, so add a couple of cells
i = 1;
function addRowCell(el) {
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
var c1 = x.insertCell(0);
var c2 = x.insertCell(1);
c2.innerHTML = fName;
i++;
}
FIDDLE
Update on your JS Fiddle:
i=1;
function addRowCell(el){
var table = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "ID";
cell2.innerHTML = fName;
i++;
}
Please check if that is the result that you were hoping for.

Categories