Delete table rows having selected id using javascript - javascript

I am trying to make the code to add and remove desired rows on selecting id in the select box. My code is below :
HTML code :
<body>
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select><br/><br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>
</body>
My javascript code :
<script type="text/javascript">
var employees=new Array(2);
for(i=0;i<2;i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include(){
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
</script>
Add button works fine. but for remove button I cant get a function to remove all the rows with selected id. Can anyone suggest me?
My code in jsfiddle : https://jsfiddle.net/noona/fNPvf/23235/

use querySelectorAll and rowIndex to achieve this. here is your updated code
var employees = new Array(2);
for (i = 0; i < 2; i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include() {
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id = id - 1;
row.id = id;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var id = document.getElementById("select_id").value - 1;
var table = document.getElementById("table");
rowsCount = table.querySelectorAll('tr[id="' + id + '"');
for (var i = 0; i < rowsCount.length; i++) {
table.deleteRow(rowsCount[i].rowIndex);
}
}
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br/>
<br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>

When adding a new row, give the newly added rows an attribute that holds it's id value. Then you can delete all the rows whose attribute value is equal to selected id in dropmenu.
you can try below:
function include(){
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
// give the new row an attribute that can identify itself
row.setAttribute("emplId",id);
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
for(var i = 0; i<table.rows.length; i++) { // iterate through the rows
var rowEmplId = table.rows[i].getAttribute("emplId");
if(rowEmplId==id) { // found a row matches the selected option
table.deleteRow(i); // remove this row
i--; // we just removed a row, so we need to adjust the cursor
}
}
}

Related

Adding new row to table with three columns Javascript html click function

Desrciption
I'd like to able to add a row using javascript with three columns to a table in html.
I am creating a table where the user can enter their own text and add the text along with two other pieces of information to the table into three columns. The current code that I have will not display the new row. The code also includes a drag and drop feature where the user can click on the row and drag it into a different position into the table.
I am asking for guidance as to why when I press the click button it does not add a new row to the table.
edit: Code is now working after update, but the else statement does not do anything.
Javascript
function addRow(mytable) {
var food = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode(document.querySelector('.input2').value);
var time = document.createTextNode(document.querySelector('.input3').value);
document.querySelector('.input').value = '';
document.querySelector('.input2').value = '';
document.querySelector('.input3').value = '';
// Get a reference to the table
if (food !== '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = food;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
//not working for some reason
else {
document.getElementById("msg").innerHTML = "Please enter a name";
}
}
javascript click
document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<div id="addRow"></div>
</table>
Few adjustments below, but more detail needed, atm only one text input for component, but can add more for cook/time
function addRow(mytable) {
var newItem = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode("Cook");
var time = document.createTextNode("time");
document.querySelector('.input').value = '';
// Get a reference to the table
if (newItem != '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = newItem;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
}
document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<tr class="draggable" id="draggable" draggable="true">
<td>Food goes here</td>
<td>Cook</td>
<td>10</td>
</tr>
<div id="addRow"></div>
</table>
<label for='component'>component</label>
<input class='input' id='component' />
<button id='btn'>add component</button>

Creating a JS function that colors a specific cell

I am trying to create a separate function that once a table has been generated, a value x and y can be placed within the input and it will highlight the desired cell a certain colour.
My issue arises when I try to select the cell specifically, my code breaks down at
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
//selector function
function SelectCell() {
//grab value from the input x and y
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
//insert the value of x and y into an array retriever
var rowIndex = document.getElementById("valy").value;
var cellIndex = document.getElementById("valx").value;
//*********BREAKS DOWN HERE*******
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
change.style.backgroundColor = "red";
//change color of specific coord
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit1">
<input type="number" id="valx" placeholder="x">
<input type="number" id="valy" placeholder="y">
<input type="submit" id="smit2">
<table id="table">
</table>
I'm not sure you can chain it like this:
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
I think what you want is:
//grab value from the input x and y
var rowIndex = +document.getElementById('valy').value;
var cellIndex = +document.getElementById('valx').value;
// Get reference to the table
var table = document.getElementById('table');
// Get the tr of the table with the index rowIndex
var tr = table.querySelectorAll('tr')[rowIndex];
// Query the selected row for all column elements and select the one at the needed index
var change = tr.querySelectorAll('td')[cellIndex];
NOTE: It's probably best to validate the values in the input before trying to retrieve the DOM element to ensure the code does not break if the user enters a non integer value or a value which is out of bounds
Since I finished it anyway:
Here is a working example
var irow = document.querySelector('#irow');
var icol = document.querySelector('#icol');
var smit1 = document.querySelector('#smit1');
var valx = document.querySelector('#valx');
var valy = document.querySelector('#valy');
var smit2 = document.querySelector('#smit2');
function GenerateTable() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
tbl.setAttribute('class', 'generated');
tbl.appendChild(tblBody);
body.appendChild(tbl);
smit1.disabled = true;
irow.disabled = true;
icol.disabled = true;
smit2.disabled = false;
valx.disabled = false;
valy.disabled = false;
}
function SelectCell() {
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
var rowIndex = valy.value;
var cellIndex = valx.value;
var change = document.querySelector('table.generated tbody').children[rowIndex].children[cellIndex];
change.style.backgroundColor = "red";
}
smit1.addEventListener('click', GenerateTable);
smit2.addEventListener('click', SelectCell);
table.generated td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.width100 {
width: 100%;
}
<body>
<div class="width100">
<input type="number" id="irow" placeholder="rows">
<input type="number" id="icol" placeholder="cols">
<input type="submit" id="smit1">
</div>
<div class="width100">
<input type="number" id="valx" disabled="true" placeholder="x">
<input type="number" id="valy" disabled="true" placeholder="y">
<input type="submit" id="smit2" disabled="true">
</div>
</body>

Button onclick event change all the select option selection in a row

I have this code highly inspired by this subject: (Adding an onclick event to a table row). It's working, when I click anywhere on the row, all the select input change their selected option to index 1.
Unfortunatly, I would like to use a button or a link from the first td of the row to make this work...
Like I'm having a link or a button on a row and when I click on it... Every select option value change to index 1
Can anyone help me? Thank you
function SetJR() {
var table = document.getElementById("TO2");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function (row) {
return function () {
var cell1 = row.getElementsByTagName("td")[1];
var cell2 = row.getElementsByTagName("td")[2];
var cell3 = row.getElementsByTagName("td")[3];
var cell4 = row.getElementsByTagName("td")[4];
var cell5 = row.getElementsByTagName("td")[5];
var cell6 = row.getElementsByTagName("td")[6];
var cell7 = row.getElementsByTagName("td")[7];
var cell1d = cell1.getElementsByTagName("select");
var cell2d = cell2.getElementsByTagName("select");
var cell3d = cell3.getElementsByTagName("select");
var cell4d = cell4.getElementsByTagName("select");
var cell5d = cell5.getElementsByTagName("select");
var cell6d = cell6.getElementsByTagName("select");
var cell7d = cell7.getElementsByTagName("select");
for (b = 0; b < cell1d.length; i++) {
var id = cell1d[b].options;
cell1d[b].selectedIndex = 1;
cell2d[b].selectedIndex = 1;
cell3d[b].selectedIndex = 1;
cell4d[b].selectedIndex = 1;
cell5d[b].selectedIndex = 1;
cell6d[b].selectedIndex = 1;
cell7d[b].selectedIndex = 1;
break;
}
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
</script>
function SetJR() {
var createClickHandler = function(row) {
return function() {
var cell1 = row.getElementsByTagName("td")[1];
var cell2 = row.getElementsByTagName("td")[2];
// ...
var cell1d = cell1.getElementsByTagName("select");
var cell2d = cell2.getElementsByTagName("select");
// ...
for (var b = 0; b < cell1d.length; i++) {
cell1d[b].selectedIndex = 1;
cell2d[b].selectedIndex = 1;
// ...
break; // what does this mean? loop will run only once?
}
};
};
var table = document.getElementById("TO2");
for (i = 0; i < table.rows.length; i++) {
var currentRow = table.rows[i];
var button = currentRow.querySelector("td:first-child button");
if (button)
button.onclick = createClickHandler(currentRow);
}
}
SetJR();
<table cellspacing="2" cellpadding="2" border="1" id="TO2">
<tr>
<td><button>Click</button></td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
</tr>
<tr>
<td><button>Click</button></td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
</tr>
</table>
Just put a <button> or <span> element in the first <td> of each row and set the onclick attribute of either to your function.
<tr>
<td>
<button onclick="SetJR()">Button</button> or <span onclick="SetJR()">Span</span>
</td>
...
</tr>

How to dynamically insert a table row with a select box with options in a table using javascript?

I am having a hard time in inserting table rows dynamically since I haven't really tried it before. What I'm supposed to do is to insert a new table row with a select box with options from the an arraylist.
So far, this is my code:
HTML
<TABLE id="dataTable">
<TR>
<TD> 1</TD>
<TD>
<select name="option">
<%for(int i = 0; i < jList.size(); i ++){%>
<option value="<%=jList.get(i).getName%>"><%=jList.get(i).getName%></option>
<%}%>
</select>
</TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
JAVASCRIPT
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var count = rowCount + 1;
var row = table.insertRow(rowCount);
//*** EDIT ***
var cell1 = row.insertCell(0);
cell1.innerHTML = count;
var cell2 = row.insertCell(1);
var element2 = document.createElement("select");
//how do i put the options from the arraylist here?
cell2.appendChild(element2);
}
also, I would also like to know how to pass a variable from the javascript function to a java servlet because every time I pass the variable count in a hidden input type, the input does not contain the count. I hope you can help me with my dilemma.
Just after you create the "select" element You can simply loop through your"arraylist" and append the options :
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var count = rowCount + 1;
var row = table.insertRow(rowCount);
//*** EDIT ***
var cell1 = row.insertCell(0);
cell1.innerHTML = count;
var cell2 = row.insertCell(1);
var element2 = document.createElement("select");
//Append the options from the arraylist to the "select" element
for (var i = 0; i < arraylist.length; i++) {
var option = document.createElement("option");
option.value = arraylist[i];
option.text = arraylist[i];
element2.appendChild(option);
}
cell2.appendChild(element2);
}
Take a look at this fiddle : https://jsfiddle.net/bafforosso/66h3uwtd/2/

How to read row wise column value using javascript

I have to validate a table column using javascript.But I am not able to get row wise column value.I am generating this table using java script function like add row and add column. I have to submit data to insert into database .Before submission I have to check quantity and perunit price should be numeric value.
But I am not able to apply appropriate javascript API to get particular row wise column value.
please check this image
I am posting the code for what i did
<script language="javascript">
// Add row to the HTML table
function addRow() {
var table = document.getElementById('my_table'); //html table
var rowCount = table.rows.length; //no. of rows in table
var columnCount = table.rows[0].cells.length; //no. of columns in table
var row = table.insertRow(rowCount); //insert a row
var cell1 = row.insertCell(0); //create a new cell
var element1 = document.createElement("input"); //create a new element
element1.type = "checkbox"; //set the element type
element1.setAttribute('id', 'newCheckbox'); //set the id attribute
element1.setAttribute('checked',true); //set the id attribute
cell1.appendChild(element1); //append element to cell
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.setAttribute('id', 'newInput'); //set the id attribute
element2.setAttribute('name', 'sl'+rowCount);
element2.setAttribute('style', 'width: 50px');
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "textarea";
element3.setAttribute('rows', '4');
element3.setAttribute('cols','40');
element3.setAttribute('id', 'newInput'); //set the id attribute
element3.setAttribute('name', 'discription'+rowCount);
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.setAttribute('id', 'newInput'); //set the id attribute
element4.setAttribute('name', 'quantity'+rowCount);
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.setAttribute('id', 'newInput'); //set the id attribute
element5.setAttribute('name', 'price'+rowCount);
cell5.appendChild(element5);
var cell6 = row.insertCell(5);
var element6 = document.createElement("input");
element6.type = "text";
element6.setAttribute('id', 'newInput'); //set the id attribute
element6.setAttribute('name', 'CST'+rowCount);
element6.setAttribute('style', 'width: 50px');
cell6.appendChild(element6);
var cell7 = row.insertCell(6); //create a new cell
var element7 = document.createElement("input"); //create a new element
element7.type = "checkbox"; //set the element type
element7.setAttribute('id', 'vat5'); //set the id attribute
element7.setAttribute('name','tax'+rowCount);
element7.setAttribute('value','vat5');
cell7.appendChild(element7);
var cell8 = row.insertCell(7); //create a new cell
var element8 = document.createElement("input"); //create a new element
element8.type = "checkbox"; //set the element type
element8.setAttribute('id', 'vat14'); //set the id attribute
element8.setAttribute('name','tax'+rowCount);
element8.setAttribute('value','vat14') ;
cell8.appendChild(element8);
var cell9 = row.insertCell(8); //create a new cell
var element9 = document.createElement("input"); //create a new element
element9.type = "checkbox"; //set the element type
element9.setAttribute('id', 'serviceTax'); //set the id attribute
element9.setAttribute('name','tax'+rowCount);
element9.setAttribute('value','serviceTax');
cell9.appendChild(element9);
}
//Alert
// delete the selected rows from table
function deleteSelectedRows() {
var table = document.getElementById('my_table'); //html table
var rowCount = table.rows.length; //no. of rows in table
for(var i=0; i< rowCount; i++) { //loops for all row in table
var row = table.rows[i]; //return a particular row
var chkbox = row.cells[0].childNodes[0]; //get check box object
if(null != chkbox && true == chkbox.checked) { //wheather check box is selected
table.deleteRow(i); //delete the selected row
rowCount--; //decrease rowcount by 1
i--;
}
}
}
// append column to the HTML table
function addColumn() {
var tblHeadObj = document.getElementById('my_table').tHead; //table head
for (var h=0; h< tblHeadObj.rows.length; h++) {
var newTH = document.createElement('th');
tblHeadObj.rows[h].appendChild(newTH); //append ne th to table
newTH.innerHTML = 'Column '+ (tblHeadObj.rows[h].cells.length); //append th content to th
}
var tblBodyObj = document.getElementById('my_table').tBodies[0]; //table body
for (var i=0; i< tblBodyObj.rows.length; i++) {
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
newCell.innerHTML = 'cell '+ (tblBodyObj.rows[i].cells.length); //append data to cell
}
}
// delete table rows with index greater then 0
function deleteAllRows() {
var tbl = document.getElementById('my_table'); // table reference
lastRow = tbl.rows.length - 1; // set the last row index
// delete rows with index greater then 0
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i); //delete the row
}
}
// delete last table column
function deleteColumn() {
var allRows = document.getElementById('my_table').rows;
for (var i=0; i< allRows.length; i++) {
if (allRows[i].cells.length > 3) {
allRows[i].deleteCell(-1); //delete the cell
} else {
alert("You can't delete more columns.");
return;
}
}
}
function generate(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
var f = document.form;
f.target = "_blank";
f.method="post";
f.action='ViewPO.jsp?rowCount='+rowCount;
f.submit();
}
function generate1(){
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
document.write(rowCount)
var a;
var b=document.myform.punitprice.value;
var c=document.myform.ptax.value;
var regexLetter = /[a-zA-z]/;
for(var j=1;i<=rowcount;i++){
var oCells = table.rows.item(j).cells;
a=oCells[3].firstChild.data;
}
if(regexLetter.test(a)){
alert('Enter Only Numeric Values For ');
return false;
}
var f = document.form;
f.target = "";
f.method="post";
f.action='purchaseAction.jsp?rowCount='+rowCount;
// f.submit();
}
</script>
<table id="my_table" align="center" border="2" cellpadding="0" cellspacing="0">
<thead><tr>
<th>Select</th>
<th>Sl.no</th>
<th>Description of Services/Goods</th>
<th>Quantity</th>
<th>Price/Unit</th>
<th>CST %</th>
<th>VAT5.5%</th>
<th>VAT14.5%</th>
<th>ServiceTax%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br>
</center>
<center>
<hr/>
<bgcolor ="red"/>
<input type="button" value="Add row" name="add" onClick="addRow()"/>
<input type="button" value="Delete selected rows" name="delete_all" onClick="deleteSelectedRows()" />
<input type="button" value="Delete all rows" name="delete" onClick="deleteAllRows()" /><br/>
<hr/>
<p>
<input type="submit" value="Save" onclick="generate1()" />
<input type="submit" value="View PO" onclick="generate()"/>
</center>
<hr/>
</form>
</div>
Help me as soon as possible.

Categories

Resources