I have a table and I am deleting the table rows using the following script:
$("#ordertable tr input:checked").parents('tr').remove();
Then I am updating the table ids as follows:
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++) {
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
var j = i+1;
$("#ordertable tr:nth-child("+j+")").find("td").eq(1).find("select").attr("id","pn_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(2).find("input").attr("id","notes_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(3).find("input").attr("id","qty_"+i);
table.rows[i].cells[4].id = "pdctid_"+i;
}
}
I need a condition in such a way that user can not allow to delete last row.
I mean in deletion If user marked last row checkbox then I should get an alert.
It seems you want to not delete the last row with a checked checkbox. So you'd get the row to be deleted, then get the row with the last checked checkbox. If they're the same row, don't delete. Otherwise, delete.
The following is just an example of putting the above algorithm to the test. Of course there is much to improve to suit your circumstance.
E.g.
function deleteRow(el) {
// Get the row candidate for deletion
var row = el.parentNode.parentNode;
// Get last checked checkbox row, if there is one
var table = row.parentNode.parentNode;
var cbs = table.querySelectorAll('input:checked');
var cbRow = cbs.length? cbs[cbs.length - 1].parentNode.parentNode : null;
// If the row to be deleted is the same as the last checked checkbox row
// don't delete it
if (row === cbRow) {
alert("Can't touch this...");
// Otherwise, delete it
} else {
row.parentNode.removeChild(row);
}
}
<table>
<tr>
<td>0 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>1 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>2 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
</table>
Related
I am trying to add an input field to each cell of my HTML table when I add a new row. The problem is that each time I click the button it only adds an input field to the first column. If I change the index number it only works for either the first or last column, but no columns in between.
<table id="table">
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
</table>
<p>Click button to test funtionality.</p>
<button onclick="AddRow()">Click Me</button>
<script>
function AddRow() {
// Get ID for table from HTML file
var table = document.getElementById("table");
// Count number of columns in table
var columnNumber = document.getElementById("table").rows[0].cells.length;
// Add row to last row in table
var row = document.getElementById("table").insertRow(-1);
// Create Input field in table
var newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("placeholder", "Raw Good Name");
newInput.classList.add("TableInput");
// Add columns to new row matching header
for (i = 1; i <= columnNumber; i++) {
var firstColumn = row.insertCell(0).appendChild(newInput);
}
}
</script>
Clone the input or simplify the script
I made the HTML valid and use an eventListener as recommended
const tb = document.getElementById("tb");
const columnNumber = document.querySelectorAll("#table thead tr th").length - 1;
const inp = '<td><input type="text" placeholder="Raw Good Name" class="TableInput"/></td>';
let cnt = 1;
document.getElementById("add").addEventListener("click",() => {
tb.innerHTML += `<tr>
<td class="right">${cnt++}</td>
${[...Array(columnNumber).keys()].map(i => inp).join("")}
</tr>`
})
.right {
text-align: right;
}
<table id="table">
<thead>
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
<thead>
<tbody id="tb">
</tbody>
</table>
<p>Click button to test funtionality.</p>
<button type="button" id="add">Click Me</button>
You need to be creating the input and appending it to the cell within the loop that creates the cells so that more than one will be created.
/* This is only here for display purposes in the Stack Overflow environment */
input { width:5em; }
<table id="table">
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
</table>
<p>Click button to test funtionality.</p>
<button onclick="AddRow()">Click Me</button>
<script>
function AddRow() {
// Get ID for table from HTML file
var table = document.getElementById("table");
// Count number of columns in table
var columnNumber = document.getElementById("table").rows[0].cells.length;
// Add row to last row in table
var row = document.getElementById("table").insertRow(-1);
// Add columns to new row matching header
// Loop should start at 0 and continue as long as you are less than
// the array length
for (i = 0; i < columnNumber; i++) {
// Create Input field in table
var newInput = document.createElement("INPUT");
// newInput.setAttribute("type", "text"); <-- Not needed: type="text" is the default
// newInput.setAttribute("placeholder", "Raw Good Name"); <-- See following line for simpler syntax
newInput.placeholder = "Raw Good Name";
newInput.classList.add("TableInput");
// If we're not on the first of last column
if(i !== 0 && i < columnNumber - 1){
newInput.type = "number"; // Make the input a number
}
row.insertCell(0).appendChild(newInput);
}
}
</script>
I am trying to change the quantity of each row based on the 'Amt' that is inputted in the last column of that row. It's a search table that's based off the Area #. Essentially I want the user to be able to input a location and move bulk items from the current area to the new area that was inputted. If the Amt would equal zero that row would be skipped and no update would take place. Otherwise it would create a new row in the database with the new data.
Link to screenshot
https://photos.google.com/photo/AF1QipP2HMqNFmv208VOOl2DvppPGiZkv7f_keD_f8tj
This is my php table code:
The values for country, region, location and placeid are stored in the dropdown.
<?php
if (isset($_GET['Placeid'])) {
$moveplace = $_GET['Placeid'];
$sql = "SELECT *
FROM Parts p, Locations l
WHERE Placeid = '$moveplace' and p.locationid = l.locationid";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
if ($i % 2 == 0) {
$bgcolor = "rgba(199, 199, 199, 0.3)";
} else {
$bgcolor = "rgba(199, 199, 199, 0.8)";
}
echo "<div>
<input type='hidden' value='".$row['id']."' name='hiddensearchid'>
<input type='hidden' value='".$row['PartDescription']."' name='movedesc'>
<input type='hidden' value='".$row['BrandName']."' name='moveBN'>
<input type='hidden' value='".$row['CategoryName']."' name='moveCN'>
<input type='hidden' value='".$row['NSN_number']."' name='moveNSN'>
<input type='hidden' value='".$row['Image']."' name='moveimage'>
<table class=searcht style='background-color:$bgcolor'>
<tbody>
<tr>
<td value='".$row['PartNum']."' name='movepart'>".$row['PartNum']."</td>
<td value='".$row['ModelNum']."' name='movemodelnum'>".$row['ModelNum']."</td>
<td>".$row['Country']."</td>
<td>".$row['Region']."</td>
<td>".$row['Location']."</td>
<td>".$row['Placeid']."</td>
<td style='width:100px' value='".$row['UnitNum']."' name='moveunitnum'>".$row['UnitNum']."</td>
<td style='width:50px;' value='".$row['QTY']."' name='moveqty'>".$row['QTY']."</td>
<th style='width:50px; border-right:none;'><input style='width:20px; text-align:center;' value='0' type=text name='moveamt'></th>
</tr>
</tbody>
</table>
</div>";
$i++;
}
echo "<tr><td></td><td><input class='submit' type='submit' value='Confirm' name='submitPlacemove' onclick=\"return confirm ('Are you sure you want to submit?')\"></td></tr></form>";
}
}
I figure I need to use some sort of JavaScript but I'm new to it. Any help is appreciated.
I assume there is a Done button that the user will press when ready to scan the table for changes and update the database.
read and store the current values of the table (before any user changes)
When Done button clicked, scan table row-by-row and compare stored value with current value
When find a change, send the data over to a PHP file whose job is to update the back-end table with the new data (Note: you will need to send both the new data AND an item id, so it knows where to put the new data)
Here is a very rough, untested, simple example of what the code might look like:
var arr_old = [];
var arr_new = [];
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let currval = $(this).find('td:nth-child(3) index').val();
arr_old.push(currval);
});
$('#btnDone').click(function(){
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let row_id = $(this).find('td:nth-child(1)').text(); //1 or 2 or ...
let newval = $(this).find('td:nth-child(3) index').val();
if ( newval !== arr_old[i+1] ){
$.ajax({
type = 'post',
url = 'path/to/your/php_file.php',
data = 'item_id=' +row_id+ '&new_val=' +newval
}).done(function(recd){
console.log('Updated row ' + recd);
});
}
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tr><th>ID</th><th>Col 1</th><th>Edit Col</th></tr>
<tr><td>1</td><td>Summat</td><td><input class="bob" type="text" value="car" /></td></tr>
<tr><td>2</td><td>Other</td><td><input class="bob" type="text" value="bike" /></td></tr>
<tr><td>3</td><td>Summat</td><td><input class="bob" type="text" value="foot" /></td></tr>
</table>
<button id="btnDone">Done</button>
If you are new to javascript, I suggest using jQuery for these reasons
References:
update list with jquery & ajax
http://learn.jquery.com/about-jquery/how-jquery-works/
SLAKS jQuery Tutorial - Use right-arrow to display next bit of text
I have two rows of a table here. When I click the checkbox in the first table row, I'm trying to target the ID of the span in the next table row. I have an alert in my code just to show me that I was successful.
What I have isn't working. I can't figure out a way to select data in the next table row when the checkbox in the first row is clicked.
<table>
<tr id="row-a">
<td>
<input type="checkbox">
<span>
some text
</span>
</td>
</tr>
<tr>
<td>
<span id="target">
some text
</span>
</td>
</tr>
</table>
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $("tr#row-a').next('tr').find('span').attr('id');
alert(spanID);
});
});
Try this:
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $(this).closest('tr').next().find('span').attr('id');
alert(spanID);
});
Example fiddle
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = myCheck.parents("tr").next().find('span').attr('id');
alert(spanID);
});
});
The change was in this line:
var spanID = myCheck.parents("tr").next().find('span').attr('id');
Which does the following:
Finds the checkbox's tr parent
Gets the next sibling node (next tr)
Finds the span
Gets its id
This is my code:
function deleteHostTable(src) {
var table = src.parentNode.parentNode.parentNode;
if(table.rows.length > 1) {
table.deleteRow(src.parentNode.parentNode);
}
}
function addHost(src) {
var table = src.parentNode.parentNode.parentNode;
var newRow = table.insertRow(table.rows.length-1);
var cell = newRow.insertCell(newRow.cells.length);
cell.innerHTML = '<input type="hidden" name = "vtierIdH" value = "vtierId" />'
cell = newRow.insertCell(newRow.cells.length);
cell.innerHTML = '<img src="images/minus.gif" onclick="deleteHostTable(this);return false;"/>';
cell = newRow.insertCell(newRow.cells.length);
cell.className = "pagetitle";
cell.innerHTML = '<input type = "text" value="hstst" />';
}
</script>
<html>
<table id="host#1" index="1">
<tr>
<td colspan="10">
<h2 align="left" class="pagetitle">Sub Account Hosts:</h2>
</td>
</tr>
<tr>
<input type="hidden" name="vtierIdH" value="<%=vtierId %>" />
<td><button id="minus" onclick="deleteHostTable(this);"/></td>
<td class="pagetitle"><input type="text" value="hstst" /></td>
</tr>
<tr>
<td><button onclick="addHost(this);"></td>
</tr>
</table>
</html>
Now, when i click the button corresponding to a button, this code deletes the uppermost row
and not the row corresponding to that button which is clicked. How can i delete the row corresponding to the button in that row?
Just change your remove function to
function deleteHostTable(src) {
var row = src.parentNode.parentNode;
row.parentNode.removeChild(row);
}
The reason it's not working with deleteRow is that it expects the index of the row to be passed while you are passing an object.
You must pass "index" to the table.deleteRow function, not the element.
function deleteHostTable(src) {
var table = src.parentNode.parentNode.parentNode;
var row = src.parentNode.parentNode;
for(var i = table.rows.length; i--; )
{
if ( table.rows[i] == row )
{
table.deleteRow(i);
return;
}
}
}
this function should work.
You also can use src.parentNode.parentNode.parentNode.removeChild(src.parentNode.parentNode)
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>