jQuery problems with parent().remove() - javascript

I am trying to clone and remove a table with jQuery, without success.
Here is an example, the table I want to operate:
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2"><img src="./images/add.gif" /><img src="./images/delete.gif" /></td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
Now, the javascript functions add() and remove():
function add(o){
var o = $(o);
var tr = o.parent().parent().parent();
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
}
function remove(o){
var o = $(o);
o.parent().parent().parent().remove();
}
add(this) works perfectly, but the remove(this) is not working, it removes just my "delete.gif" image. What am I doing wrong please?

Look at the jsFiddle.
I used jQuery for what you need.
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2">AddDelete</td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
$(function() {
$(document).on('click', '.adicionar', function(event){
var o = $(event.target);
var tr = o.closest('table');
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
});
$(document).on('click', '.remover', function(event){
var o = $(event.target);
var table = $(o.closest('table'));
table.remove();
});
});

Instead of this parent.parent.parent madness (it's madness, yes it is) why don't you use
element.closest("tr")
to find the row it's in?
This approach will work consistently.

Related

Javascript XPath table loop td's

I am trying to create a Chrome Extension that will extract some data from a table. I want to transform the TD's of the TR's in simple lines with each column separated by a pipe | character, ex:
01/01/2020 | XX | 57,43 | |
02/01/2020 | YY | 11,22 | |
Here is a part of it:
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
To iterate over it, I use XPath like this:
function DOMtoString(doc) {
let path_tr = '(//div[#class="contborda"])[4]/table[3]/tbody/tr[position()>1]';
var tr = doc.evaluate(path_tr, doc, null, XPathResult.ANY_TYPE, null);
let alertText = '';
let x = tr.iterateNext();
while (x) {
alertText += x.textContent;
x = tr.iterateNext();
}
return alertText;
}
Here I get the table (ignoring the first TR with column names), but the result is this (just some part of it):
<br> <br> 21/02/2020 <br> Concessionárias<br> <br> 57,43 <br> <br> Visualizar<br> enviar por email <br><br>
I see that XPath is adding BR's on it.
I try to loop over the TD's of these TR's with no success like this:
let path_td = '//td';
var td = tr.evaluate(path_td, tr, null, XPathResult.ANY_TYPE, null);
What is the correct way that I can interact over the TD's and get the raw text of them with no BR's?
Use innerText instead of textContent to avoid line breaks. You can use Document.querySelector() instead of XPath which will make DOM manipulation much easier.
CSS Selectors:
function DOMtoString() {
let lines = [];
let trs = document.querySelectorAll(
'div.contborda > table:nth-of-type(2) > tbody > tr:not(:first-child)'
);
trs.forEach(tr => {
let line = [];
let tds = tr.querySelectorAll('td');
tds.forEach(td => line.push(td.innerText.trim()));
lines.push(line.join('|'));
});
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>
If you have any other reasons you want to stick to using XPath, then you should use dot .// when you want to select nodes relative to nodeContext:
XPath:
function DOMtoString() {
let lines = [];
let path_tr = '//div[#class="contborda"]/table/tbody/tr[position()>1]';
let tr = document.evaluate(path_tr, document, null, XPathResult.ANY_TYPE, null);
let x = tr.iterateNext();
while (x) {
let line = [];
let path_td = './/td';
var td = document.evaluate(path_td, x, null, XPathResult.ANY_TYPE, null);
let y = td.iterateNext();
while (y) {
line.push(y.innerText.trim());
y = td.iterateNext();
}
lines.push(line.join('|'));
x = tr.iterateNext();
}
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>

How to pass the selected checkbox rows to a function

I have to pass the selected rows to a function( ). From the below code, I am able to get the value of selected checkbox but could not get the entire row. Please help me on how to get the entire selected rows and pass those rows to a function.
my html code:
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
My jQuery Code:
$('#div_table').click(function() {
var result = []
$('input:checkbox:checked', tableControl).each(function() {
result.push($(this).parent().next().text());
});
alert(result);
});
The selected rows should be passed to the below function:I have to use these rows one by one and store.
function invokeAllEligibleSaves(result){
alert(result)
}
It will be very much useful for me If i get a working code. Thanks in advance.
One way to achieve that is like this:
First : get a reference to the input element that triggered the function. From this element, you can reach the .closest() parent that has the tag <tr>.
Second: This can then be queried for all of its <td> .children() and each child will either have .text() or .html() to report back. I think in your case, you are interested in the text part.
Third: You will need to push all .text() values in a separate array, that will be your row. Then push that row into another array result. So your result will be an array of arrays.
$('#div_table').click(function() {
var result = [] // create an empty array for all rows
$('input:checkbox:checked').each(function() {
var row = []; // create an empty array for the current row
//loop through all <td> elements in that row
$(this).closest('tr').children('td').each(function(){
// add .text() or .html() if you like
row.push($(this).text());
});
// now push that row to the result array
result.push(row);
});
alert(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank">100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1">100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2">100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
You just need an additional .parent() in your result.push statement to get the whole row, because you're only getting the cell so far:
result.push($(this).parent().parent().next().text());
This would be a more effective solution for your problem. The drawback with the accepted answer is, it will get triggered whenever & wherever you click inside the table (even when you click on a text).
Here it gets updated only when a checkbox is selected.
$(document).ready(function() {
$('input:checkbox').on('change', function() {
var result = [];
$('input:checkbox:checked').each(function() {
var rowText = '';
$(this).parent().siblings().each(function() {
rowText += $(this).text() + ' ';
});
result.push(rowText.trim());
});
alert(JSON.stringify(result));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>

jQuery select all data from selected rows

I have a table. I want to get name, lastname, email from all selected rows (check is set). Maybe name, lastname, email will be arrays.
How can I do it?
I've tried this:
var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
result.push($(this).parent().next().text());
});
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
But I get only selected names. How can I get the other columns?
This is one possible way of doing things . I set a class for every type of column. You can use that to find out all the other information of the checked rows.
Observe the console. you get all the information in one object which you can then use for whatever further functions you might want it to do
var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
var obj={};
var parent=$(this).parent().parent();
obj.name=(parent.find( ".name" ).text());
obj.last=(parent.find( ".last" ).text());
obj.country=(parent.find( ".country" ).text());
obj.email=(parent.find( ".email" ).text());
result.push(obj);
});
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td class="name" id="name_1">Petya</td>
<td class="last" id="last_1">L1</td>
<td class="country" id="country_1">Country1</td>
<td class="email" id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td class="name" id="name_2">Kolya</td>
<td class="last" id="last_2">L2</td>
<td class="country" id="country_2">Country2</td>
<td class="email" id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td class="name" id="name_3">Vasya</td>
<td class="last" id="last_3">L3</td>
<td class="country" id="country_3">Country3</td>
<td class="email" id="email_3">Email3</td>
</tr>
<button id="btn">Click</button>
Instead of clicking a button every time you want to sum up your results, i would suggest you handle the result object anytime a checkbox is clicked, this makes for a more stable state and handles dynamic changes better. Consider changing your code to look like:
var tableControl = $('#mytable');
//An object that maps checkbox id to an object containing name, last and email
var result = {};
tableControl.find('input:checkbox').click(function() {
var key = $(this).attr('id');
//If checkbox clicked and not checked, then remove object from map
if(!$(this).is(":checked")){
delete result[key];
return;
}
var row = $(this).parent().parent();
//Get children based on the start of the id string
var firstName = row.children("td[id^='name']").text();
var lastName = row.children("td[id^='last']").text();
var email = row.children("td[id^='email']").text();
result[key] = {
name: firstName,
last : lastName,
email: email
}
});
This way, anytime a checkbox is clicked, the results object will update immediately to reflect the desired value. The result object would look something like this:
{
"check_1": {
"name": "Petya",
"last": "L1",
"email": "Email1"
},
"check_2": {
"name": "Kolya",
"last": "L2",
"email": "Email2"
},
"check_3": {
"name": "Vasya",
"last": "L3",
"email": "Email3"
}
}
https://jsfiddle.net/p35kz2u1/6/
var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
// Get the entire text
//alert($(this).closest('tr').children('td').text());
//alert($(this).parent().next().find('td').text());
// Get each column
$(this).closest('tr').children('td').each(function(e){
alert($(this).text());
});
result.push($(this).closest('tr').children('td').text());
});
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
<button id="btn">Get Data</button>
var tableControl= $('#mytable');
$("#btn").click(function () {
var result = [];
tableControl('input[type="checkbox"]:checked').each(function() {
var nodeArray = $(this).parents('tr').find('td');
var innerArray = [];
for(var i = 1; i < nodeArray.length; i++) {
if(nodeArray.hasOwnProperty(i)) {
innerArray.push(nodeArray[i].text());
}
}
if(innerArray.length > 0) {
result.push(innerArray);
}
});
alert(result);
});
please try out this, i have not tested, but i think it should do what you want.
You can use something like below. I modified your inner query to go to parent and looks for siblings.
var tableControl = $('#mytable');
$("#btn").click(function() {
var result = [];
$('input:checkbox:checked').each(function(item) {
$(this).parent().siblings().each(function() {
result.push($(this).text())
});
});
alert(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
</table>
<button id ="btn">Click Me</button>

ID select of td using JQuery

What I am trying to do is onLoad essentially, find all id's of each td, that has a number 1-7 and replace it with the image that corresponds with that number i.e.
<td id="7" class="level">7</td>
would change the 7, the content to ...
<td id="7" class="level"><img src="../img/CL7.png" alt=""></td>
So what i have so far is as follows:
$(document).ready(function()
{
$("td").click(function()
{
var findID =$(this).attr('id');
var replace ="<img src=\"../img/cl"+ findID +".png\" alt=''>";
function ReplaceCellContent(findID, replace)
{
return $("tbody tr td.level:contains('" + findID + "')").html(replace);
}
var myStringArray = [1,2,3,4,5,6,7];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
ReplaceCellContent(findID, replace);
}
});
});
So it will go, find all of the ID's of the td's onclick of each td. I want it to do this to ALL of the ids ranging from 1-7, when the page loads.
I am somewhat new to JQuery/JavaScript,I DO HAVE THE SCRIPT LINK TO JQUERY API THROUGH GOOGLE FYI, so any explanation would be greatly appreciated as well. I was trying to use the loop at the bottom to loop through all of the possible numbers and just plug them in but i can't think of how to connect each back to of its original td, which had had that ID.
the HTML Table that the JQuery needs to change looks like this, written out:
<table class="sortable">
<thead>
<tr>
<th>Player Name</th>
<th>Level</th>
</tr>
</thead>
<tbody>
<tr>
<td>Krack</td>
<td id="7" class="level">7</td>
</tr>
<tr>
<td>Lively</td>
<td id="6" class="level">6</td>
</tr>
<tr>
<td>Bamon Williams</td>
<td id="6" class="level">6</td>
</tr>
<tr>
<td>Sinister Char</td>
<td id="5" class="level">5</td>
</tr>
<tr>
<td>Senior BoomBox</td>
<td id="5" class="level">5</td>
</tr>
<tr>
<td>Blitzking</td>
<td id="4" class="level">4</td>
</tr>
<tr>
<td>Hadooooken</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>Jumpman2392</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>ALEC*</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>Frokido</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>B. McOxbig</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>[MES] Koko</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>PinkStrank</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>papa von</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>Nuski</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>LunchBoxes</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>Grenade65</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>[MGS]TOAD</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>NoahS</td>
<td id="1" class="level">1</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
jQuery is great, but I don't recommend it for everything and especially not until you really have a good understanding of JavaScript, so this solution only uses jQuery to register a function to be called when the page is ready for interaction:
// When the document is ready, run the following function:
$(function(){
// Get all the TD elements:
var allTheTDs = document.querySelectorAll("td.level");
// Loop through the array of all the TD elements
for(var i = 0; i < allTheTDs.length; ++i){
// Check to see if the current TD has an ID of 7 or less
if(allTheTDs[i].id <=7 ){
// Remove the current content of the TD
allTheTDs[i].innerHTML = "";
// Create a new img element
var img = document.createElement("img");
// Configure the new img element to have a src attribute value
// that is based on the id value
img.src = "../img/CL" + allTheTDs[i].id + ".png";
// Give the img an alt to match the src, just to show
// it works
img.alt = "../img/CL" + allTheTDs[i].id + ".png";
// Append the new image into the current TD
allTheTDs[i].appendChild(img);
}
}
});
Here's a working fiddle: https://jsfiddle.net/96hkhy4j/4/
You may do something like this
$(document).ready(function() {
var myStringArray = [1,2,3,4,5,6,7];
for (var i = 1; i <= myStringArray.length; i++) {
var findID = i;
var replace ="<img src=\"../img/cl"+ findID +".png\" alt=''>";
ReplaceCellContent(findID, replace);
}
function ReplaceCellContent(findID, replace) {
return $("tbody tr td.level:contains('" + findID + "')").html(replace);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sortable">
<thead>
<tr>
<th>Player Name</th>
<th>Level</th>
</tr>
</thead>
<tbody>
<tr>
<td>Krack</td>
<td id="7" class="level">7</td>
</tr>
<tr>
<td>Lively</td>
<td id="6" class="level">6</td>
</tr>
<tr>
<td>Bamon Williams</td>
<td id="6" class="level">6</td>
</tr>
<tr>
<td>Sinister Char</td>
<td id="5" class="level">5</td>
</tr>
<tr>
<td>Senior BoomBox</td>
<td id="5" class="level">5</td>
</tr>
<tr>
<td>Blitzking</td>
<td id="4" class="level">4</td>
</tr>
<tr>
<td>Hadooooken</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>Jumpman2392</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>ALEC*</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>Frokido</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>B. McOxbig</td>
<td id="2" class="level">2</td>
</tr>
<tr>
<td>[MES] Koko</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>PinkStrank</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>papa von</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>Nuski</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>LunchBoxes</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>Grenade65</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>[MGS]TOAD</td>
<td id="1" class="level">1</td>
</tr>
<tr>
<td>NoahS</td>
<td id="1" class="level">1</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
Just replace line 3 with this..
$(document).ready(function()
{
$("tbody td").each(function()
{
var findID =$(this).attr('id');
var replace ="<img src=\"../img/cl"+ findID +".png\" alt=''>";
function ReplaceCellContent(findID, replace)
{
return $("tbody tr td.level:contains('" + findID + "')").html(replace);
}
var myStringArray = [1,2,3,4,5,6,7];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
ReplaceCellContent(findID, replace);
}
});
});
Hi you just add jQuery and try this way
<script src="jquery-2.2.1.min.js"></script>
<script>
$('table tr td:nth-child(2)').each(function() {
var id =$(this).attr('id');
$(this).html('<img src="../img/CL'+id+'.png" alt="">')
});
</script>

Find the sibling td element with jquery

I have a table that looks like this:
<table>
<tr>
<td class='class1' id='id1'></td>
<td class='class2' id='id2'></td>
<td class='class3' id='id3'></td>
<td class='class4' id='id4'><button id='editButton'></button></td>
</tr>
<tr>
<td class='class1' id='id1'></td>
<td class='class2' id='id2'></td>
<td class='class3' id='id3'></td>
<td class='class4' id='id4'><button id='editButton'></button></td>
</tr>
</table>
The code below shows me id4:
$("#editButton").on("click", function(){
alert($(this).parent().attr("id"));
});
Now I need to reach id3 which is the closest one. The functions .next('class3') and .closest('class3') do not help me or i am using them in a wrong way. Please help me
1st : id must be unique
so your code should like
<table>
<tr>
<td class='class1' id='id1'></td>
<td class='class2' id='id2'></td>
<td class='class3' id='id3'></td>
<td class='class4' id='id4'><button class="editButton"></button></td>
</tr>
<tr>
<td class='class1' id='id5'></td>
<td class='class2' id='id6'></td>
<td class='class3' id='id7'></td>
<td class='class4' id='id8'><button class="editButton"></button></td>
</tr>
</table>
and in js
$(".editButton").on("click", function(){
alert($(this).closest('tr').find('td:nth-child(3)').attr("id"));
});

Categories

Resources