swapping rows using a javascript - javascript

I've a multiple number of rows which is generated by a for condition, with 2 icons up and down. On click of up the selected row should move one step up, and on click of down the selected row should move one step down
<html>
<head>
<body>
<form name="myForm">
<table id="mainTable" border="1" width="100%">
<script>
document.write('<tr>')
document.write('<td>')
document.write('row1')
document.write('</td>')
document.write('</tr>')
document.write('<tr>')
document.write('<td>')
document.write('row2')
document.write('</td>')
document.write('</tr>')
document.write('</table>')
document.write('<table>')
document.write('<tr>')
document.write('<td>')
document.write('<input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"</input>')>
document.write('<input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"</input>')>
document.write('</td>')
document.write('</tr>')
document.write('</table>')
</script>
</table>
</form>
</body>
</head>
</html>
<script>
var mainTable = document.getElementById("mainTable");
function getRowIndex(el)
{
while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );
if( el )
alert(el.rowIndex);
return el.rowIndex;
}
function swapRowUp(chosenRow) {
if (chosenRow.rowIndex != 0) {
moveRow(chosenRow, chosenRow.rowIndex-1);
}
}
function swapRowDown(chosenRow) {
if (chosenRow.rowIndex != mainTable.rows.length-1) {
moveRow(chosenRow, chosenRow.rowIndex+1);
}
}
function moveRow(targetRow, newIndex) {
if (newIndex > targetRow.rowIndex) {
newIndex++;
}
var mainTable = document.getElementById('mainTable');
var theCopiedRow = mainTable.insertRow(newIndex);
for (var i=0; i<targetRow.cells.length; i++) {
var oldCell = targetRow.cells[i];
var newCell = document.createElement("TD");
newCell.innerHTML = oldCell.innerHTML;
theCopiedRow.appendChild(newCell);
copyChildNodeValues(targetRow.cells[i], newCell);
}
//delete the old row
mainTable.deleteRow(targetRow.rowIndex);
}
function copyChildNodeValues(sourceNode, targetNode) {
for (var i=0; i < sourceNode.childNodes.length; i++) {
try{
targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
}
catch(e){
}
}
}
</script>
i'm unable to perform the swap operation, i get cellIndex as null

You can use some sensible JavaScript
up.addEventListener("click", function moveRowUp() {
var row = this.parentNode.parentNode,
sibling = row.previousElementSibling,
parent = row.parentNode;
parent.insertBefore(row, sibling);
});
for some sensible HTML
<table>
<tbody>
<tr>
<td> 1 </td>
<td> filler </td>
</tr>
<tr>
<td> 2 </td>
<td> <button id="up">up</button> </td>
</tr>
</tbody>
</table>
Live Example

Related

Make table via value

How do I do that JavaScript will print in my HTML page a table via the value the user will choose?
That the JS script:
let numCol = document.getElementById('txtColumns').value;
let numRow = document.getElementById('txtRows').value;
let go = document.getElementById('btn');
let table = document.getElementById('table');
let td = "<td></td>" * numCol;
let tr = ("<tr>" + td + "</tr>") * numRow;
go.addEventListener('click', function(){
table.innerHTML = tr;
})
That the HTML code:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table">
<!--Here I want to print the table-->
</table>
</div>
</table>
<script src="script.js"></script>
</body>
</html>
At first I thought about that way with the script but its only appear as a NaN and not table...
The following syntax:
let td = "<td></td>" * numCol;
does not produce numCol cells, so the following syntax:
let tr = ("<tr>" + td + "</tr>") * numRow;
does not produce numRow rows also.
So, the whole source code should be:
let go = document.getElementById('btn');
let table = document.getElementById('table');
go.addEventListener('click', () => {
let numCol = document.getElementById('txtColumns').value; //Get the value of txtColumns at the button click moment.
let numRow = document.getElementById('txtRows').value;
let td = "",
tr = "";
for (let i = 0; i < numCol; i++) {
td = td + "<td></td>";
}
for (let i = 0; i < numRow; i++) {
tr = tr + "<tr>" + td + "</tr>";
}
table.innerHTML = tr;
})
<table class="workTable">
<tr>
<td>
<input type="number" placeholder="Columns Number" id="txtColumns">
</td>
<td>
<input type="number" placeholder="Rows Number" id="txtRows">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button id="btn">
Print
</button>
</td>
</tr>
<div>
<table id="table" border="1">
<!--Here I want to print the table-->
</table>
</div>
</table>

How to UNDO the added row(s) WITHOUT DELETING the table heading

Right now, i have a reset button to reset all rows that have been added. The problem is it also deletes my table heading which i want to keep.
Any ideas to keep the table heading?Thanks guys.
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
$('[name="reset"]').click(function() {
$('#one tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add Row</button>
<button type="reset" name="reset">Reset Row</button>
<table id="one">
<thead>
<th>No.</th>
<th>Name</th>
<th>Gender</th>
</thead>
<tbody>
</tbody>
</table>
Just select <TBODY>
$('#one tbody tr').remove();

To delete a row dynamically from a table using javascript

I need help in deleting the row one by one from the bottom of the table on clicking the delete row button.
Issue:
I have used the javascript function to delete a row from my table, instead of deleting the row one by one from the bottom it is getting deleted as a whole except the first 2 rows. I need to delete the rows from the bottom one by one except the first 2 rows when the delete button is clicked .
This is my code
<html>
<head>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname"/></td>
<td><input type="text" name="qty"/></td>
<td><select name="brand"/>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
this help you :
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
final code :
<html>
<head>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
Before going to the loop deleting the rows, you should check first the number of rows. or you can remove the loop since you are just deleting one row only which is the last row (rowCount-1);
Try this:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 2){
//for(var i =1; i < 2; i++) {
// var row = table.rows[i];
table.deleteRow(rowCount-1);
//}
}
else{
alert("Cannot delete all the rows.");
}
}
catch(e) {
alert(e);
}
}
Here is the working code, you didnt break the execution after deleting a row, thats why it was deleting all the rows
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
else{
table.deleteRow(i);
rowCount--;
i--;
break;
}
}
}
catch(e) {
alert(e);
}
}
See if this Helps :
$('#tbl1').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#tbl1').append('<tr><td><input type="text" class="txtBox" /></td><td><input type="button" value="X" /></td></tr>')
});
Here is something to work with an HTML Snippet
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbl1" style="border: 1px solid blue">
<tr>
<td>
<input type="text" class="txtBox" />
</td>
<td>
<input type="button" value="X" />
</td>
</tr>
</table>
<p>
<input type="button" value="Add">
</p>

Put dynamic table on chained select box using jQuery

I have a form for Purchase Requisition and I created 3 chained select box (category, subcategory, product description) my reference to create those chained select boxes is this website http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/ the problem is that I want to request many products the question is how? and I want to put all of that I requested in database. Somehow I found codes they used javascript but the only working row is the first row only. When I select eg. Category: Office Supplies all of the subcategory select box(rows) are affected. Here is my code:
<html>
<head>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("select#desc").attr("disabled","disabled");
$("select#type").change(function(){
$("select#desc").attr("disabled","disabled");
$("select#desc").html("<option>wait...</option>");
var id = $("select#type option:selected").attr('value');
$.post("select_desc.php", {id:id}, function(data){
$("select#desc").removeAttr("disabled");
$("select#desc").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
var descr = $("select#desc option:selected").attr('value');
if(cat>0 && type>0 && descr>0)
{
var result = $("select#desc option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
<input type="button" value="Add" onclick="addRow('tableID')" />
<input type="button" value="Delete" onclick="deleteRow('tableID')"
/>
<table id="tableID">
<tr>
<td></td>
<td>Category</td>
<td>SubCategory</td>
<td>Product Description</td>
</tr>
<tr>
<td><input type="checkbox" name="chkbox[]" /></td>
<td>
<select id="category" name="category[]">
<?php echo $opt->ShowCategory(); ?>
</select>
</td>
<td>
<select id="type" name="type[]">
<option value="0">choose...</option>
</select>
</td>
<td>
<select id="desc" name="desc[]">
<option value="0">choose...</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="confirm" />
</form>
<div id="result" name="result[]"></div>
</body>
</html>
Please I need help!

dynamically filter rows of a HTML table using JavaScript

So I have this table:
<table border="1" align="center">
<tr>
<td>Broj_pu</td>
<td>Naziv_pu</td>
<td>ID</td>
<td>Naselje</td>
<td>zupanija</td>
</tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(document.getElementById('broj_pu').value, 'broj_pu')" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(document.getElementById('naziv_pu').value, 'naziv_pu')" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(document.getElementById('ID').value, 'ID')" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(document.getElementById('naselje').value, 'naselje')" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(document.getElementById('zupanija').value, 'zupanija')" /></td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>1</td>
<td>Sljeme</td>
<td>ZAGREBACKA</td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>2</td>
<td>Zagreb-dio</td>
<td>ZAGREBACKA</td>
</tr>
<!-- A lot of rows -->
...
</table>
And also I have started this JavaScript:
<script type="text/javascript">
function Filter(text, column_name){
var x = document.getElementByClassName("row");
var i = 0;
var y;
if (text != ""){
switch (column_name){
case "broj_pu":
for (i = 0; i < x.length; i++){
y = x[i].getElementByTagName("td");
if((y[0].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naziv_pu":
y = x[i].getElementByTagName("td");
if((y[1].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "ID":
y = x[i].getElementByTagName("td");
if((y[2].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naselje":
y = x[i].getElementByTagName("td");
if((y[3].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "zupanija":
y = x[i].getElementByTagName("td");
if((y[4].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
}
}
}
</script>
Now, I need to filter the table as the user inputs letters to the text fields, but I have no idea how to edit the display document as I enter the data.
Anyone have an idea?
EDIT1:
So I edited the script but it doesn't seem to work. What did I do wrong?
This question is reminding me of how java script is nasty without any framework support :)
However I have sorted-out this issue for you ( tested on firefox 10.0.2).
check the complete working solution on jsfiddle
please remember this is just working example , you might need to write ALL-Browser compliant script .
script:
var filters=['hide_broj_pu','hide_naziv_pu','hide_ID','hide_naselje','hide_zupanija'];
function ExcludeRows(cls){
var skipRows=[];
for(i=0;i<filters.length;i++)
if(filters[i]!=cls) skipRows.push(filters[i]);
var pattern=skipRows.join('|')
return pattern;
}
function Filter(srcField){
var node=srcField.parentNode;
var index=srcField.parentNode.cellIndex;
//all the DATA rows
var dataRows= document.getElementsByClassName("row");
//ensure that dataRows do not have any filter class added already
var kids= dataRows.length;
var filter ='hide_'+srcField.id;
var pattern = ExcludeRows(filter);
var skipRow = new RegExp(pattern,"gi");
var searchReg =new RegExp('^'+srcField.value,'gi');
var replaceCls= new RegExp(filter,'gi');
for(i=0; i< kids ; i++){
//skip if already filter applied
if(dataRows[i].className.match(skipRow)) continue;
//now we know which column to search
//remove current filter
dataRows[i].className=dataRows[i].className.replace(replaceCls,'');
if(!dataRows[i].cells[index].innerHTML.trim().match(searchReg))
dataRows[i].className=dataRows[i].className +' '+ filter;
}
}
HTML
<table border="1" align="center">
<tr><td>Broj_pu</td><td>Naziv_pu</td><td>ID</td><td>Naselje</td><td>zupanija</td></tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(this)" /></td>
</tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>1</td><td>Sljeme</td><td>ZAGREBACKA</td></tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>2</td><td>Zagreb-dio</td><td>ZAGREBACKA</td></tr>
</table>
CSS
.hide_broj_pu,
.hide_naziv_pu,
.hide_ID,
.hide_naselje,
.hide_zupanija
{display:none}
For Javascript Table Search, Try:
<p>Search: <input type="text" id="searchTerm" onkeyup="doSearch()" /></p>
<table id="dataTable">
<script>
function doSearch() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("searchTerm");
filter = input.value.toUpperCase();
table = document.getElementById("dataTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
</script>

Categories

Resources