Unable to remove the selected input rows from a table - javascript

I have multiple input tags in a table of type "checkbox". I need to remove the complete row of selected checkbox.
I am using the following function to remove the selected rows:
function removeSelected( tblname )
{
var tbl = document.getElementById(tblname);
var rowcount = tbl.rows.length;
if (tbl.rows.length > 1)
{
for ( var i = 0 ; i < tbl.rows.length ; i++)
{
var row = tbl.rows[i];
var chkselect = row.cells[0].getElementByTagName("input").item(0);
var attr = trimString(row.cells[0].getElementByTagName("input").item(1).value);
var attr1 = trimString(row.cells[0].getElementByTagName("input").item(2).value);
if (chkselect.checked)
{
tbl.deleteRow(i);
i = 0;
}
}
}
}
And My html is as below:
<table id="myTable" border = "0">
<tr border = "0">
<td><input type="checkbox" name="checkbox" id = "checkbox" value = "hen">hen</input></td>
</tr>
<tr>
<td><input type = "checkbox" name="checkbox1" id="checkbox1" value = "cock">cock</input></td>
</tr>
</table>
<br>
<button onclick="removeSelected("myTable")">Try it</button>
When I check the "hen" checkbox it should delete the hen row and when I check "cock" it should delete the cock row. However, I am unable to delete the selected one.
What am I doing wrong?

As AleJuliet said, you should fix syntax errors.
And to delete rows, you should start from the end, because the rows are shifted
function removeSelected( tblname ) {
var tbl = document.getElementById(tblname);
for ( var i = tbl.rows.length - 1 ; i >= 0 ; i--) {
checkbox = tbl.rows[i].getElementsByTagName("input")[0];
if(checkbox.checked){
tbl.deleteRow(i);
}
}
}
<table id="myTable" border = "0">
<tr border = "0">
<td><input type="checkbox" name="checkbox" id = "checkbox" value = "hen">hen</input></td>
</tr>
<tr>
<td><input type = "checkbox" name="checkbox1" id="checkbox1" value = "cock">cock</input></td>
</tr>
</table>
<br>
<button onclick="removeSelected('myTable')">Try it</button>

Related

Checkbox toggle to create string concatenation or make variable blank

I'm trying to create a function where if the checkbox is unchecked then the variable will become blank. If it is checked then the variable will take the input and concatenate it with some text.
I keep getting the input value instead of a blank variable.
<script>
function myFunction() {
var input = document.getElementById("fabric").value;
var check = document.getElementById("check");
if (input.trim() =='' || check.checked == true){
input == '';
} else {
input = 'Fabric: ' + document.getElementById("fabric").value;
}
console.log(input)
}
</script>
<table>
<thead>
<button onclick="myFunction()">Submit</button>
<th><input type="checkbox" id="check">Test</th>
</thead>
<tbody>
<td><input id="fabric" placeholder="Input"></td>
</tbody>
</table>
Looks like you can simplify a bit. You probably also intend to use = instead of ==
function myFunction() {
var input = document.getElementById("fabric").value;
var check = document.getElementById("check");
if (check.checked !== true) {
input = '';
} else {
input = 'Fabric: ' + document.getElementById("fabric").value;
}
console.log(input)
}
<table>
<thead>
<button onclick="myFunction()">Submit</button>
<th>
<input type="checkbox" id="check">Test</th>
</thead>
<tbody>
<td>
<input id="fabric" placeholder="Input">
</td>
</tbody>
</table>

Using JavaScript to add new row to table but how to I set the variables to be unique if I clone?

I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>

oninput event in html works fine till <form></form> is added?

I am adding rows in table and deleting, this works fine. using oninput="" event i am also able to calculate the total cost by calling javascript function.
Now, the moment i add <form></form>, neither am able to add rows nor moving any forward. I am new to javascript, and have no clue what is going on. please help somebody.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i <= arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Inside the form tags buttons tend to do the default action which is submit.
So change your button from,
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
to
<input type="button" onclick="myCreateFunction()" value="Create row">
<input type="button" onclick="myDeleteFunction()" value ="Delete row">
You have to add Input tag instead of button tag. Because button tag in form specifies default submit event on-click so your form submitted when you add any row and also refresh.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<input type="button" onclick="myCreateFunction()" value="Create row" />
<input type="button" onclick="myDeleteFunction()" value="Delete row" />
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i < arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>

why my javascript code dosen't work(about search and filter bar)

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>a1</title>
<link rel="stylesheet" href="a1.css" />
<script src="a1.js"></script>
</head>
<body>
<form id = "gallary" method="get" action="">
<div id="searchBox">
<input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>
<select name="genre" id ="filterBar">
<option>Genre</option>
<option>Baroque</option>
<option>Mannerism</option>
<option>Neo-classicism</option>
<option>Realisim</option>
<option>Romanticism</option>
</select>
<input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()" />
</div>
</form>
<div id="artistBox">
<table>
<caption>Paintings</caption>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Artist</th>
<th>Year</th>
<th>Genre</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="05030.jpg"/></td>
<td>Death of Marat</td>
<td>David, Jacques-Louis</td>
<td>1793</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="120010.jpg"/></td>
<td>Potrait of Eleanor of Toledo</td>
<td>Bronzino, Agnolo</td>
<td>1545</td>
<td>Mannerism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="07020.jpg"/></td>
<td>Liberty leading the people</td>
<td>Delacroix, Eugene</td>
<td>1830</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="13030.jpg"/></td>
<td>Arrangement in Grey and Black</td>
<td>Whistler, James Abbott</td>
<td>1871</td>
<td>Realisim</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="06010.jpg"/></td>
<td>Mademoiselle Caroline Riviere</td>
<td>Ingres, Jean-Auguste</td>
<td>1806</td>
<td>Neo-classicism</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
enter code here
above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).
I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;
var filter = document.getElementById("filterBar").value;
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[1];
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script. These get evaluated when the script is loaded but destroyed when the the script file is finished loading. That is the "searchFunction" does not know about the values of these tags.
Consider the updated code: (see it in action at: Plunker)
<script type="text/javascript">
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
console.log(input);
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
var filter = document.getElementById("filterBar").value;
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
} // <-- Missing
}
</script>

Search box for table

Given this table:
<table class="tbllist searchtbl" cellpadding=2 cellspacing=0 style="width: 70%">
<tr>
<th class="hidden">ID</th>
<th>Number Plate</th>
<th>Chassis Number</th>
<th>Trailer Make</th>
<th>Year</th>
<th>Axles</th>
<th></th>
</tr>
<tr class='tbl'>
<td class='hidden'>3</td>
<td>
<input type=text style = 'width: 75px' class='centered' id='trnumberplate_3' name='trnumberplate_3' value='T212ABS' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trnumberplate", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trchassisnumber_3' name='trchassisnumber_3' value='AJSDGASJH' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trchassisnumber", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trmake_3' name='trmake_3' value='LOW LOADER' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trmake", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 50px' class='centered' id='tryear_3' name='tryear_3' value='2009' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","tryear", this.value ,"trid","3","1","",this, "false")'>
</td>
<td>
<input type=text style = 'width: 25px' class='centered' id='traxles_3' name='traxles_3' value='3' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","traxles", this.value ,"trid","3","1","",this, "false")'>
</td>
<td class='delbtn'>
<button id='trailers_3' title='DELETE THIS ITEM (3)?' onclick='event.preventDefault(); delitem("trailers","trid","3","trailers.php","#workspace")'><img src='/icons/delete.png' ></button>
</td>
</tr>
</table>
I have the following search function:
function searchbox() {
// text input search for tables (such as trip history etc)
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.toUpperCase().split(" ");
//create a jquery object of the rows
var jo = $(".tbllist").find("tr").not("tr:first"); // exclude headers
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
})
It will loop through table td's to check if the searched value is available and filter rows. It is not filtering if the td contains an input text element with the searched value.
Update:
if ($t.find("input").val().toUpperCase().indexOf(data[d]) > 0) {
return true;
}
Now works but will only matches the first column of the table.
JSFiddle: https://jsfiddle.net/fabriziomazzoni79/30d52c9z/
Change jo.filter() like this:
jo.filter(function (i, v) {
var txt = '';
$(v).find("input").each(function(n,e){
txt += e.value;
});
for(var d=0; d<data.length; d++){
if (txt.search(data[d])>=0) {
return true;
}
}
return false;
})
Fiddle here.

Categories