How to fix given row to avoid delete using .remove function - javascript

I created a table where in can add and remove dynamically. I just have a little problem where it comes to deleting a row. I want my first row to be fixed because when I used remove() it deletes the row that I given.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
</div>
Script:
<script>
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
$('#customFields td:last').remove();
});
});
</script>
I used last function to delete the row but this only delete one textfield. How can I delete this by 4? Any help would appreciated!!

tr represents the row and td represent the row's single cell.
You should read and explore about HTML tables
$('#customFields tr:last').remove();
Working Demo
and to keep first row always , Count the tr length , and do the delete operation
$("#removeRow").click(function()
{ if($('#customFields tbody tr').length== 1){
// only one row left
alert("Cant delete first row")
}else
{
$('#customFields tr:last').remove();
}
});
And Since your thead has a tr too . So delete using this selection
$('#customFields tbody tr:last').remove();
it will delete tr from tbody only

you should select last row, instead of last table data(td). I mean in $('#customFields td:last').remove(); statement, instead of using td:last , please use tr:last.
i fixed it in this fiddle

Related

How to Create dynamic tbody onclick of button using javascript or jquery

I have this code:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('button').click(function() {
//Add row
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="row_no" type="text" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
When I click on the button Add row, it appends a row to the table.
But now, I have a textbox in the HTML. I want to append the table to generate rows based on the value of:
<input name="row_no" type="text" placeholder="Type Your Number of row" />
How do I achieve this?
Here's what you're looking for:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('[name=row_no]').text();
$('button').click(function() {
var rows = $('[name=row_no]').val();
// If rows are at maximum 10,
if (!(rows > 10)) {
// then add rows
for (var i = 0; i < rows; i++) {
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
}
}
else {
alert("Error: Too many rows!\n" +
"Maximum allowed: 10\n" +
"- Inserted: " + rows);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input name="row_no" type="number" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
</body>
What changed?
You needed to get the value inserted in the textfield, this can be achieved using, in this case: $('[name=row_no]').val();, so I valorised it as rows variable and then the only thing to add was a cycle that creates as many rows as the user inserts.
I also changed<input name="row_no" type="text" placeholder="Type Your Number of row" />to <input name="row_no" type="number" placeholder="Type Your Number of row" />. This little change allows the user to insert only integers and this is a nice solution to avoid time-loss because of writing a new function to validate values inserted.
Edit:
Added a control on about how many rows the user can insert with if (!(rows > 10)) condition (if you need more or less rows, the only thing to edit is the number)

How to empty table in javascript?

I cant delete the row contents of a table, but what if I want to delete the rows too?
My Javascript code: (I want all the rows to disappear except the first one.)
function deleteAll() {
for ( var i = 0; i <= table.rows.length; i++){
table.rows[i].cells[0].innerHTML = "";
table.rows[i].cells[1].innerHTML = "";
table.rows[i].cells[2].innerHTML = "";
}
}
My HTML table:
<body>
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</th>
<tr>
<td>Frank</td>
<td>Nenjim</td>
<td>19</td>
</tr>
<tr>
<td>Alex</td>
<td>Ferreira</td>
<td>23</td>
</tr>
</table>
</div>
<div class="tab tab-2">
First Name :<input type="text" name="fname" id="fname">
Last Name :<input type="text" name="lname" id="lname">
Age :<input type="number" name="age" id="age">
<button onclick="deleteAll()">Delete All</button>
</div>
</div>
<script src="tableEdit.js"></script>
</body>
So, the Javascript code above doesn't satisfy me because I want only the first row to remain. I don't want empty rows.
You can use the jQuery remove() function as described in this example to delete all rows except the (first) header row:
$('#table tr:not(:first)').remove();
You may instead want to delete just the rows of body section (inside <tbody>) as mentioned in this post:
$('#table > tbody > tr').remove();
for(var i = 1;i<table.rows.length;){
table.deleteRow(i);
}
If you want to remove data rows only then use
$("#table tr").remove();
And if you want to empty table with header then use
$("#table").empty();

Displaying rows in a table first with checked checkbox

I have table displayed with checkboxes in each row like this-
Html code : -
<table>
<tr>
<td><input type= "checkbox"></td>
<td>Name1</td>
<td>Role1</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name2</td>
<td>Role2</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name4</td>
<td>Role4</td>
</tr>
<tr>
<td><input type= "checkbox"></td>
<td>Name3</td>
<td>Role3</td>
</tr>
</table>
I also have a button 'Sort'. When I click on the button sort, all those rows which have checkboxes as checked should be displayed first and all other rows after them. The result would look something like this -
How can this be implemented?
Using jquery you can parse each <tr> and check if their child checkbox is check then add them to a new table as first or last child. then replace the old table with the new one.
$(document).ready(function(){
$('#sort').on('click', function(){
var newTable = $('<table class="table"></table>');
$('.table').find('tr').each(function($index, $value){
if($(this).find('input[type=checkbox]').is(':checked')){
newTable.prepend($(this));
} else {
newTable.append($(this));
}
});
$('.table').replaceWith(newTable);
});
});
this should work but i havn't tested it yet.
Hopes it helps !
Nic
You can use sort() and is(':checked') to sort rows and then empty table and append sorted content. DEMO
var sorted = $('table tr').sort(function(a, b) {
if($(b).find('td:first-child input').is(':checked')) {
return 1;
} else {
return -1;
}
})
$('button').click(function() {
$('table').empty().html(sorted);
})
please try this
$('input').each(function(e,i){
if(!i.checked){
var tr=$(i).closest('tr');
$(tr).parent().append($(tr).remove());
}
});

Select specific table cell in JavaScript

I have a HTML like this:
<table id="laboral">
<tr>
<td><input type="text" name="start"/></td>
<td><input type="text" name="end"/></td>
<td><textarea name="desc"></textarea></td>
<td><button type="button" onclick="saveValues(this);createRow('laboral')"> + </button></td>
</tr>
</table>
What I want is to save the values in the three cells (2 inputs and 1 textarea).
The button creates another row just like the first, with the same inputs and names. The problem is that I don't know how to access THIS row, I mean, the row who owns the button.
I tried with this.parentNode.parentNode but didn't work.
Try this
<table id="laboral">
<tr>
<td><input type="text" name="start"/></td>
<td><input type="text" name="end"/></td>
<td><textarea name="desc"></textarea></td>
<td><button type="button" onclick="saveValues(this)"> + </button></td>
</tr>
</table>
var inputVals = [];
function saveValues(elm) {
// button td tr tbody table
var table = elm.parentNode.parentNode.parentNode.parentNode;
// iterating through the first row cells
for (var i = 0; i<table.rows[0].cells.length-1; i++) {
// the current cell
var cell = table.rows[0].cells[i];
// pushing the input elm's value into the array
inputVals.push(cell.childNodes[0].value);
// retrieving the pushed value
alert(inputVals[i]);
}
}
Fiddle example
You can modify the code.
You're passing a reference to the button into saveValues, so within saveValues the first argument will refer to the button. Let's call that argument btn. btn.parentNode will be the td containing the button, and `btn.parentNode.parentNode will be the tr containing that td. So:
function saveValues(btn) {
var tr = btn.parentNode.parentNode;
// Work with `childNodes` and the `childNodes` of those children to get the values
}

How to add row in html table on top of specific row?

I have a table, and each row has a button to add a new row on top of it. Each row has new inputs.
I know how to add a row on top of the table, but not on top of each row that I'm clicking on the button. Would anyone have a tip on how to solve it? I might be able to do it, but the solution I see is very complicated, and I'm sure there must be a smarter solution.
Oh, also I don't know how to update the parameter sent in the insertNewRow(id) function.
So far this is what I have:
<script type="text/javascript">
function insertNewRow(id){
var row = document.getElementById("bottomRow");
var newrow = row.cloneNode(true);
console.log(newrow);
var newInputs = newrow.getElementsByTagName('input');
var allRows = row.parentNode.getElementsByTagName('tr');
row.parentNode.insertBefore(newrow, row);
var i=row.rowIndex;
console.log(i);
}
</script>
<table id="myTable">
<tr>
<td>Title1:</td>
<td></td>
<td>Title2:</td>
<td></td>
<td>Title3:</td>
<td></td>
<td></td>
</tr>
<tr>
<td><input class="c1" readonly maxlength="9" size="7" id="gTop" type="text" value ="11"></td>
<td> <-></td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lTop" value="33"></td>
<td>=</td>
<td id="rv1"><input id="rvTop" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td></td>
<td>x</td>
</tr>
<tr id="bottomRow">
<td><input class="c1" readonly maxlength="9" size="7" id="gBottom" type="text" value =""></td>
<td> </td>
<td id="l1"><input class="c2" style="width:35px;" maxlength="9" size="7" type="text" id="lBottom" value="11"></td>
<td>=</td>
<td id="rv1"><input id="rvBottom" input class="c2" style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
<td><button type="button" onclick="insertNewRow(1)">+</button></td>
<td>x</td>
</tr>
</table>
In the onclick attribute, instead of just calling insertNewRow(), do something like
insertNewRow.apply(this);
The this keyword inside the onclick attribute is a reference of the clicked element. With insertNewRow.apply(this), we'll be calling insertNewRow() and at the same time, assign the this keyword inside that function call to the clicked element or in this case, the button (if we don't do that, this inside insertNewRow() will be a reference to the Window object instead). Then in, your insertNewRow() function, check if the current element being clicked on is a tr element. If not, go up by one level and see if that element is a tr element. Keep doing that until you get to the first tr element. So, basically you'll be searching for the closest tr element.
<button type="button" onclick="insertNewRow.apply(this);">+</button>
function insertNewRow(){
var row = null,
el = this;
// Get the closest tr element
while (row === null)
{
if (el.tagName.toLowerCase() === 'tr')
{
row = el; // row is now the closest tr element
break;
}
el = el.parentNode;
}
// Rest of the code here
}​
JsFiddle
If you're still not sure what Function.apply() is, take a look at the documentation here.

Categories