Here is my code:
<body>
<div id="metric_results">
<div id="form">
<form name="myForm" >
...//get course IDnumber and course score
</form>
</div>
<div id="table">
<table id="TABLE" border = '1'>
</table>
</div>
<script type="text/javascript">
//when click on "add" button,call "addTable" function.
document.getElementById("add_button").onclick = function() {addTable()};
document.getElementById("delete_button").onclick = function() {DeleteTableRow()};
var stock = new Array();
var i = 0;
function addTable() { //create table with 3 column(idnumber,score,checkbox)
var c = document.createElement("INPUT");
c.setAttribute("type", "checkbox");
stock[i] = new Array(id, score);//id= course ID number,score=course score, get from form
//Create table row and append it to end of table
var tr = document.createElement('TR');
for (j = 0; j < 3; j++) {
var td = document.createElement('TD');
if(j == 2){
td.setAttribute("id","check_box"+(i+1));
td.appendChild(c);}
else{
td.appendChild(document.createTextNode(stock[i][j]));}
tr.appendChild(td);
}
table.appendChild(tr);
i=i+1
}
// Delete courses that their checkbox is on.
function DeleteTableRow(){
var check_boxes=new Array();
for(j=0; j<i ;j++){
check_boxes[j]= document.getElementById("check_box"+(j+1));
if(check_boxes[j].checked==true){document.getElementById("TABLE").deleteRow(j+1);}
}
</script>
</body>
I create a form which get course idnumber and course score.At first, when I fill the form, javascript creates a table so when I click the "add" button, I can add courses. Now, I want to add another function named DeleteTableRow() to delete the selected rows.
When I create the table for each course,I create a checkbox column and set "id" for each rows checkbox(td.setAttribute("id","check_box"+(i+1));) so in the DeleteTableRow() function I use getElementById("check_box"+(j+1)) in the for loop.
Everything is OK but I can't check the value of the check box and I can't delete the selected rows. what should I do and how do I check it?
Your main problem is that in your addTable function you set the id attribute on the table cell, rather than the checkbox. Naturally, cells don't have a checked attribute. You could fix this by doing the setAttribute('id', ...) on c, before the loop.
Note there are a few strange things about your code - for example, you should really use the literal [] when defining a new array, rather than the new Array() call; but having said that there doesn't seem to be any need for the check_boxes array in the first place, since you never use it.
In any case, your code would be a lot simpler if you used something like jQuery, which is pretty much the default for doing DOM manipulation in Javascript these days.
Related
I have a table I've built in an app that when I click delete removes all rows following the row that was deleted on submit. That means that the table looks good to the user with just that one row removed, but when it hits the viewmodel on post action, those subsequent rows aren't included.
I've added some pretty complex code that goes all over the place to edit the index values of the rows but that ended up confusing the problem even more with some values replacing others and some other values just being set to 0. I know there has to be a more simple way.
I set this example back to the more simplified version where the delete appears to work well but then doesn't include any subsequent values in the viewModel when it hits the controller.
Here is the HTML Table
<input type="button" value="Add" class="button is-primary" id="btnAdd" />
<table id="tblPart" style="table-layout:fixed; width:100%;">
<thead>
<tr>
<th>
Part Number
</th>
<th>
Quantity
</th>
<th></th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.NumberModel.Count(); i++)
{
<tr >
<td >
#Html.TextBoxFor(modelItem => Model.NumberModel[i].PartNum, new { id = $"part{i}", required = "required", #class = "partTest" })
</td>
<td>
#Html.TextBoxFor(modelItem => Model.NumberModel[i].Quantity, new { type = "number", min = "0", id = $"quantity{i}", required = "required" })
</td>
<td>
<input type='button'
onclick='Remove(this)'
value='Remove' />
</td>
</tr>
}
</tbody>
</table>
Here is the JS
<script>
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
//console.log(row + name);
var index = 0;
var table = $("#tblPart")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
</script>
Thank you for your assistance.
When you delete the row, all subsequent rows index is wrong, you need to re-index the remaining rows on delete. If you for instance delete row with index 3 and then you have rows 0-2 and rows 4-6, 4-6 will be left out since there is no index 3, to fix this, you need to reindex the id and name attributes on the form fields after delete, also, you should consider using const and let in your function as var should be used for global variables, lastly, I added jquery tag to your post as you are mixing javascript and jquery in your code:
function Remove(button) {
//Determine the reference of the Row using the Button.
const row = $(button).closest("TR");
const name = $("TD", row).eq(0).html(); //this seems unnecessary
let index = 0; //this seems unnecessary
const table = $("#tblPart")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
//re-index
$('#tblPart tbody tr').each(function(i, el) {
//get the form fields
const $partnuminput = $(el).find('input[name*="PartNum"]');
const $quantityinput = $(el).find('input[name*="Quantity"]');
//use the iterator parameter of .each to set the index correctly
$partnuminput.attr("name", $partnuminput.attr("name).replace(/\d+/g, i);
$partnuminput.attr("id", $partnuminput.attr("id").replace(/\d+/g, i);
$quantityinput.attr("name", $partnuminput.attr("name).replace(/\d+/g, i);
$quantityinput.attr("id", $partnuminput.attr("id").replace(/\d+/g, i);
});
}
I am given an assignment where I have to perform crud operations with Javascript array. well, I am not expecting the whole code I will just put down the things I am trying and getting problems within, now I have to achieve the following:
1. fill the data from form fields values on form submit
2. get data into an html table
3. each row in table row must have edit and delete button
4. on clicking delete button the current row from the table should be deleted along with the array element
5. on clicking edit button the current row data should appear in the respected form field and again on submitting the data should get replace the current array element.
this is my code:
//main array to store and get data from form
let formData = [];
//get form
let form = document.getElementById('main-form');
//get table body
let tableBody = document.querySelector('#data-table > tbody');
//initialize delete and update button
let btnUpdate = '<button class="btn btn-primary btn-edit">Edit</button>';
let btnDelete = '<button class="btn btn-danger btn-dlt">Delete</button>';
form.addEventListener('submit', function(e) {
e.preventDefault();
//storing form fields values as array to formData array as multidimensional array
formData.push([
btnUpdate,
btnDelete,
document.getElementById('name').value,
document.getElementById('location').value,
document.getElementById('age').value,
document.getElementById('qualification').value,
document.mainForm.gender.value,
document.getElementById('address').value.trim()
]);
//get data from array and show in table
//outer loop iterates rows
for (let row = 0; row < formData.length; row++) {
let tableRow = document.createElement('tr');
//inner loop iterates over cells
for (let cell = 0; cell < formData[row].length; cell++) {
let tableCell = document.createElement('td');
tableCell.innerHTML = formData[row][cell];
tableRow.append(tableCell);
}
tableBody.appendChild(tableRow);
}
with this, I am able to get the data from the array and show it in the table, but the rows are repeating i guess because of the for loop its getting all the rows from the array everytime on form submit.
any help if why the rows are repeating in the table on form submit. i am only stuck at this problem.
https://medium.com/#etiennerouzeaud/a-simple-crud-application-with-javascript-ebc82f688c59
I hope this article will answer all your questions .
https://github.com/CodAffection/Pure-JavaScript-CRUD-Operations-with-Html
I have an array of checkboxes group into class='year'. I would like to call a function in JS when a checkbox is checked.
The html is,
<table class="inner" id="searchTable">
<search>Exam Type:<th>
<?php
foreach($exams as $key=>$value):
echo "<tr><td class='left'><input type='checkbox' class='year' id='$key' name='$key' value='$value'
if ($category['selected'])
{
echo ' checked';
}
> $value</td></tr>";
endforeach; ?>
</table>
This table is inside a form. but I am too worried about the form at the moment.
The JS should create a table with a row when any checkbox is checked.
function yearTable(){
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
var empty = document.createTextNode("year.value");
/*var empty = document.createTextNode("");*/
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
document.getElementByClassName('year').onchange = yearTable;
I have tried using .onchange and .clicked but neither do anything when a box is checked.
Also I need the value checked in the JS.
I tried year.value but that doesn't work. Prviously I has a select options menu with id = 'exam' and I was able to get the value using exam.value but I can't figure out how to do soemthing equivalent for these checkboxes.
Any help would be greatly appreciated.
Thanks
While an html document may contain only one element with a specific id, there can be several elements with the same class.
So, there is no such a function as document.getElementByClassName. There is a function document.getElementsByClassName, and it returns an array of elements, so could call that function and then iterate over its return value, setting the needed callbacks.
Also, the code you posted must have thrown an exception at this line:
document.getElementByClassName('year')
So if you looked at developer tools in Chrome or Firebug in Firefox, you would probably see an error.
Got it,
function yearTable(){
var year = this.value;
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
if (this.checked){
var empty = document.createTextNode(year);
}
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
var checkboxes = document.getElementsByClassName('year');
for(var index in checkboxes){
checkboxes[index].onchange = yearTable;
}
Thanks
Please no jquery.
I've seen several examples of this where the input field already exists on the page before you update it, but I'd like to dynamically create the input field and then populate it with information available from the page (hence current_value variable defined above this code snippet):
for (i=0; i<tables.length; i++) {
(function(i) {
var sp = document.createElement('span');
var act_table = document.createElement('table');
act_table.id = 'act-tests-' + i;
act_table.style.display = 'none';
var test_name_input = document.createElement('tr');
test_name_input.innerHTML = '<tr><td width="100px">Name</td><td><input type="text" class="wideValue testName input"></td></tr>';
test_name_input.setAttribute('value', current_rule);
act_table.innerHTML ='<tbody><tr>LOTS OF TABLE ROWS HERE</tr></tbody>';
act_table.insertBefore(test_name_input,act_table.firstChild);
sp.appendChild(act_table);
}
The field is being shown but not populated with my current_value.
Any help greatly appreciated.
In your example you set an attribute to the tr, instead of the created input field.
try to do this:
document.getElementsByClassName("input")[you_index].setAttribute("value", current_value);
Here an example: http://jsfiddle.net/35g0ks0t/
I am taking user input from a form and trying to create a table from that input. The input should determine the number of rows and columns. I have tried the following but I am getting nothing. I am a bit stumped. Any help appreciated.
JS
function makeChart(){
var table = document.createElement("table");
var taskName = document.getElementById("taskname").value + "</br>";
var numDays = document.getElementById("days").value + "</br>";
var howOften = document.getElementById("times").value + "</br>";
var rows=table.insertRow(howOften);
var cols=rows.insertCell(numDays);
document.getElementById("holdTable").appendChild(table);
table.appendChild(rows);
table.appendChild(cols);
}
HTML
<div id="holdTable">
<form id="chartInput">
<label for="taskname">Task</label>
<input id="taskname" type="text" placeholder="Enter the task name here"> <br>
<label for="days">How many days</label>
<input id="days" name="days" type="number" min="1" max="7"> <br>
<label for="times">How many times a day</label>
<input id="times" name="times" type="number" min="1" max="4"> <br>
<input id="createChart" type="button" value="Make the chart" onClick="makeChart();"> <br>
</form>
</div>
I think you need to use loop.
for(var i = 1;i<=howOften;i++)
{
var row = table.insertRow(-1)
for(var i = 1;i<=numDays;i++)
{
row.insertCell(-1)
}
table.appendChild(row);//edited
}
Try using this in place of this 2 lines:
var rows=table.insertRow(howOften);
var cols=rows.insertCell(numDays);
EXPLANATION
insertRow function inserts new table row(<tr>) in at index position specified in brackets. It inserts only one row. So if index is 0 <tr> will be appended to the beggining of the table as a first row. Similarly -1 appends <tr> as the last row in the table.
insertCell function inserts cell(<td>) in at index position of the row(<tr>). Same as above -1 means it adds new cell at the last position in the row.
Each row than has to be appended to the table or stored in an array for later use therefore I added table.appendChild(row); which adds each consecutive row to the array.
table.insertRow and tableRow.insertCell take, as their parameters, the index at which you wish to do the insertion. You are, instead, passing a string which contains your field values appended to an HTML BR tag (a malformed one at that).
Furthermore, to add text to an element you need to create text nodes with document.createTextNode and append those nodes to the element in question.
Finally, cols should be a child of rows, not of table. So your line, table.appendChild(cols) is in error as well.
Beyond those comments, I cannot go further. I am not sure what exactly you're looking for in the outputted table structure. It seems to me you are wanting one row with two columns, but Dharman's answer shows that he reads it as you wanting multiple rows. Consider updating your question with some markup showing the desired table.
Edit: Using your comment for more information, I wrote the following code demo for you to try: http://jsfiddle.net/Kkb7n/ . For the sake of demonstration, I have it use the "task name" as the text content of the created cells.
Modified JS in case JSFiddle is down:
var makeChart = function () {
var table = document.createElement('table'),
taskName = document.getElementById('taskname').value,
numDays = document.getElementById('days').value, //columns
howOften = document.getElementById('times').value, //rows
row,
r,
col,
c;
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
col.appendChild(document.createTextNode(taskName));
}
}
document.getElementById('holdTable').appendChild(table);
};