Delete row using inout field - javascript

I am creating table, and want to remove row by id using input field. (if input field matches with id then the row must be deleted)
can not figure it out.
Your help is much appreciated
`
<body onload="addRow()">
<table id="myTable" style="display:none">
<tr>
<th class="borderless">ID</th>
<th>Name</th>
<th>Username</th>
<th>Gender</th>
<th>Country</th>
</tr>
<tbody id="myTableBody">
</tbody>
</table>
<button type="button" id="buttonShow" onclick="showTable()">Show Table</button>
<button type="button" id="buttonAdd" onclick="addRow()" disabled>Add a new row</button>
<br>
<label>
<input class="input1" type="text" name="todoTags"/>
<button class="dellbtn" id="buttonDell"onclick="delRow()" disabled>Delete row</button>
</label>
`
`
function showTable(){
document.getElementById("myTable").style.display = "block";
document.getElementById("buttonAdd").disabled = false;
document.getElementById("buttonDell").disabled = false;
}
const btn = document.querySelector('.dellbtn')
const userTags = []
`
Here is my: JSfiddle

What you could do is changing the addRow() method so it adds a data-attribute to each row, in the <tr>. You can achieve this goal by adding this when creating the row :
row.setAttribute("row-id", tr.length - 1);
Then, when you want to delete it, you can simply search the
row that has the data-attribute that you just input. And it will look like this :
function delRow() {
const value = document.getElementById("valueToDelete").value;
document.querySelector('[row-id="' + value + '"]').remove();
}
I created a fork to your JSFiddle that you can check right here.
Hope it helps ! Good luck :)

Not exactly what you're asking, but this method might work better for you. It uses a delete button for each row so you can decide which one to delete. Then it uses a delegate listener to enable the delete buttons
const table = document.querySelector('#theTable tbody');
let c = 1
const addRow = () => {
table.innerHTML += `<tr><td>${c} data</td><td>${c} data</td><td><button class='delete'>delete</button></td></tr>`;
c++
}
// delegate listener for the delete button
table.addEventListener('click', e => {
if (e.target.classList.contains('delete')) {
e.target.closest('tr').remove();
}
})
<table id='theTable'>
<th>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td></td>
</tr>
</th>
<tbody>
</tbody>
</table>
<button onclick='addRow()'>Add Row</button>

Related

jQuery appendTo ignoring last element

I'm trying to append a copy of an element to the bottom of the parent element. It seems to append everything above the last element within the parent. Live example on JSFiddle
var count = 1;
$("#addBtn").click(function(){
$('#trid1').clone().appendTo('table#exampleTable > tbody');
count++;
$('#trid1').last().prop('id', 'trid'+count);
$('#trid'+count+' > th').html(count);
});
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable">
<thead>
<tr>
<th scope="col">c1</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>
I would change the id before appending the new element to the DOM.
Anyway I slightly refactored your code with that strategy in mind and better dealt with the current index every time you click the add button. The latest index gets saved in a data attribute in the table.
$("#addBtn").click(function(){
const latestIndex = $('#exampleTable').data('latest-index');
let i = latestIndex+1;
const newRow = $('#trid1').clone();
newRow.prop('id', `trid${i}`);
newRow.data('index', i);
newRow.text(i);
newRow.appendTo('table#exampleTable > tbody');
$('#exampleTable').data('latest-index', i);
});
button{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" id="exampleTable" data-latest-index="1">
<thead>
<tr>
<th scope="col">Rows</th>
</tr>
</thead>
<tbody>
<tr id="trid1" class="trclass">
<th scope="row">1</th>
</tr>
</tbody>
</table>
<button type="button" id="addBtn">Add</button>

How do I get and pass the field of the row having class="name" in the following html?

<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata(parameter)">Fetch Details</button>
</td>
</tr>
</tbody>
In the above html, I want that the function fetchdata('parameter') to contain the text content of the td which has a class of name and is hidden, as the parameter.
OR
I need a way in which I can get the text content of the td having class of name in my javascript function.
i.e.
function fetchdata() {
const name = document.somethingThatGivesMeName()
}
NOTE: There are going to be multiple rows that I may require to get the name of so I can't directly do document.queryselector('.name')
Sorry, This might be pretty simple but I can't quite figure it out.
When clicking the button find the first row up in the tree relative to the button with the closest method. Then from the row select the element with the class name and read the textContent or innerText of that element.
const buttons = document.querySelectorAll('.js-fetch-details');
function fetchDetails(event) {
const row = event.target.closest('tr');
const name = row.querySelector('.name').textContent;
console.log(name);
}
buttons.forEach(button => button.addEventListener('click', fetchDetails));
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button class="js-fetch-details">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
You just need the quotes ':
function fetchdata(value){
console.log(value)
}
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata('parameter')">Fetch Details</button>
</td>
</tr>
</tbody>
or you can use event listener and data value:
document.querySelectorAll('button').forEach(el => {
el.addEventListener('click', e => {
e = e || window.event;
e = e.target || e.srcElement;
console.log(e.dataset.value)
})
})
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button data-value="parameter">Fetch Details</button>
</td>
</tr>
</tbody>
You can use document.getElementsByClassName('name')
This will get all the elements that have class of name.
I would put the listener on the <tbody> instead.
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.parentNode.parentNode.querySelector('.name').textContent;
console.log(name);
}
});
UPDATE
closest would also work
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.closest('tr').querySelector('.name').textContent;
console.log(name);
}
});
First you get all elements with class="name", then you pick just (the first) one with the attribute "hidden".
It's a way to do it anyway.
function fetchdata() {
const tds = document.getElementsByClassName("name")
for(let i = 0; i < tds.length; i++){
if(tds[i].getAttribute("hidden") != null) {
console.log(tds[i].innerHTML)
}
}
}
<table>
<tr>
<td class="name">gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td class="name">1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
With jQuery you can just do:
function fetchdata() {
console.log($('.name[hidden]').html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
Note that you need to have a table around your structure for any of this to work properly. You can't have tbody, tr and td outside a table.
If you use document.getElementsByClassName you will get what you want.
However, if there will be a case where more than one instance of that class name will occur, then you need to iterate through the classes and get their values.
The following should solve your problem
<html>
<head>
<script>
function fetchdata(){
var data = document.getElementsByClassName("data");
var t = data.length;
for(i = 0; i< t; i++){
var content = data[i].innerHTML;
alert (content);
}
}
</script>
<body>
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="data" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

What is the tag in HTML that refer to element in DOM?

In line8:- it has element.parentElement.remove(element), here the element it refers to what tag in HTML?
Note:- This the fiddle code, in case you need it.
Javascript
var td4 = document.createElement('td');
td4.setAttribute("id", "td4");
td4.innerHTML = <button
onclick=remove(this.parentElement)>X</button> *line4
tr.appendChild(td4);
function remove(element){
element.parentElement.remove(element) **line8**
}
HTML
<div class='table'>
<table id="table">
<th>
<tr>
<td>Task</td>
<td>Date</td>
<td>Urgency</td>
<td>Done</td>
</tr>
</th>
<button onclick=clearAll()> Clear All </button>
</table>
</div>
You should use template strings.
// You'll need to access to the tr element.
// Also, I would recommend use const instead of var
const tr = document.querySelector('tr');
const td4 = document.createElement('td');
td4.setAttribute("id", "td4");
// You'll need to use the parentElement property twice, because the button will be inserted into the 'td' and you need access to the 'tr'
td4.innerHTML = `<button
onclick=remove(this.parentElement.parentElement)>X</button>`
tr.appendChild(td4);
function remove(element){
element.parentElement.remove(element)
}
<div class='table'>
<table id="table">
<th>
<tr>
<td>Task</td>
<td>Date</td>
<td>Urgency</td>
<td>Done</td>
</tr>
</th>
<button onclick=clearAll()> Clear All </button>
</table>
</div>
Read more about Accessing the DOM here.
element in element.parentElement.remove(element) is td4.
You should add console to print the tag easily.
function remove(element){
console.log(element);
element.parentElement.remove(element) **line8**
}

calcul jQuery does not work

I try to change value by default with a calcul : value by default * quantity / 100. In my script something does not work because nothing happened, I can't find what! (jQuery is very new for me...)
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseFloat($("#valquantite").text() );
$("#nutrition > tbody > tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(1).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition" >
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
What i try to do is that the first column after the name retrieves the quantities from a table (different for each row), then I retrieve the values ​​by default columns energie_kj, energie_kcal, proteines, etc .. from a table (there are 60 Columns !! they are already calculated by default, I do not need to do any conversion). Some cells contain text (example: nc, traces, <) that I want to display as text. Then I have to calculate the total of each column (ignoring cells that contain text). That's my problem! I posted another question for the same problem with a code in js that works almost but not completely ... here: Javascript problems with NaN
Thanks in advance for your answers.
Hope this will help you. Replace your code with following : I've just parse your valeur variable and replaced > sign when calling .each function and applied Id=nutrition to table rather than tbody tag.
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseInt($("#valquantite").text());
$("#nutrition tbody tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
The issue may be, we don't know exactly what it is you're trying to calculate or where the data comes from. The valQuantite to which you refer, does that change for each row? If so, why is it defined outside of the each function? If not, why does it refer to a value from the first row of the table?
Doing a little research, you seem to want to take the quantity column and use that along with the energie kJ column to calculate... something. I'd suggest using classes for the three columns, valquantite, energie-kj, and energie-kcal, which you can then use to manipulate the individual columns in a meaningful way. Using $(this).find("td").eq(2).text() is only as good as the coder -- what if the column layout changes? Instead, simply use $(this).find(".energie-kj").text() and you're good.
Now, having gotten to displaying the kj as you'd like (by taking the qty and multiplying it by the kj, then rounding), you can calculate the kCal by dividing that number by 4.1868 and rounding as you'd like.
But note, I've modified your code -- the quantity seems to change with each row, so I've moved valQuantite inside the each statement. Also, I can't stress enough, I've commented my code to the point of silliness. Doing so makes it far easier to track what each line of code is SUPPOSED to be doing, as well as what it's actually doing. And use your console, it is your debugging FRIEND! lol
$(function() {
// When the button is clicked, calculate the values.
$("#calcul").click(function(e) {
// First, make sure the button doesn't submit...
e.preventDefault();
// Each row is handled individually, so
$("#nutrition > tbody > tr").each(function() {
// First, get the qty for this row
var valeur = parseFloat($(this).find(".valquantite").text());
/****
* Here is a case. We have hard-wired to use the
* third column of the table for the original val,
* but we could also add a class for this col and
* reference that: $(this).find(".energie-kj");
****/
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var energyKJ, energyKCal;
// If the energie kJ value is numeric, we do the first
if ($.isNumeric(valeurOrigin) === true) {
// calculate some value from the energie kJ and qty,
energyKJ = valeurOrigin * valeur / 100;
// 1 kCal = 4.1868 kJ, so do the conversion
energyKCal = (energyKJ/4.1868).toFixed(2);
energyKJ = energyKJ.toFixed(2);
} else {
// If the energie kJ value is NOT numeric, we simply
// set the displayed value to this
newValeur = $(this).find("td").eq(2).text();
}
$(this).find(".energie-kj").text(energyKJ);
$(this).find(".energie-kcal").text(energyKCal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr>
<td>Pain au lait, préemballé:</td>
<td class="valquantite"><strong>35gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr>
<tr>
<td>Some other thing...:</td>
<td class="valquantite"><strong>45gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr> <tr>
<td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />

how to get values of columns for a selected row through jQuery on click of element calling method to retrieve value

here i am trying to fetch values of a particular column for a selected row via jquery.In Following code i have two rows which do not have any id.I tried following way and getting both rows value for that column appending each other.how to get value for that row only using jquery only.I want to call test function on click of that element, dont want to use http://jsfiddle.net/SSS83/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function test(){
var id = $(".use-address").closest("tr").find('td:eq(2)').text();
alert(id);
}
</script>
</head>
<body>
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td class="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Glas</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
<tr>
<td class="nr"><span>30</span>
</td>
<td>Some Street 2</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Not sure why you don't want to use jQuery Click event!!
Any way, if you want to stick with your test function, you need to tell the function from where it got called.
so change the
<button type="button" class="use-address" onclick="test();">Use</button>
to
<button type="button" class="use-address" onclick="test(this);">Use</button>
And update your test function as
function test(el) {
var id = $(el).closest("tr").find('td:eq(2)').text();
alert(id);
}
Enjoy!!
If you change your mind you can use the following code
jQuery('document').ready(function() {
jQuery('.use-address').on('click',function() {
var id = $(this).closest("tr").find('td:eq(2)').text();
alert(id);
})
});
Based on a click of a TD:
$('td').on('click',function() {
//get the column of the TD
var myCol = $(this).index();
//loop through the rows of this table, get the TD in the same column
$(this).parent('table').find('tr').each(function() {
var colValue = $(this).find('td').eq(myIndex).html()
}
})
"colValue" in the loop will grab the contents of the TD at that position.

Categories

Resources