Get td parent and tr child - javascript

I need to get the value "TEST1" from the first TD clicking on the button. I tried the Javascript but it doesn't work.. The print gave me undefined.
<table style="width:100%">
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td><button class='x' type='button' onclick='openindex()' >value='button'</button></td>
</tr>
</table>
Here is my Javascript function, I can't figure out what I'm doing wrong because I find the closest Tr but the child property doesn't work
function openindex(){
var $row = $(this).closest("tr");
$tds = $row.find("td:nth-child(1)").value;
alert($tds);
}

You are calling openindex() without an explicitly context, so this (inside it) will be window and not the element.
You could pass it:
onclick="openindex.call(this)"
but you should avoid using onclick attributes in the first place and bind your functions with jQuery().on instead.
jQuery('button').on('click', openindex);

I think you just need to use
$tds = $row.find("td:nth-child(1)").text();
instead of
$tds = $row.find("td:nth-child(1)").value;
You should also use the var keyword to set the variable so it is not a global variable and since it is just returning a string there is no need for the $ so
var tds = $row.find("td:nth-child(1)").text();
Or another way altogether would be
$('.x').click(function () {
var $row = $(this).closest("tr");
var tds = $row.find('td').first().text();
alert(tds);
})

Related

Add element to passed jQuery selector

I'm trying to pass a table to a function and then get the rows using jQuery. What am I doing wrong here?
sortTable($('#myTable'));
function sortTable(targetTable)
{
var rows = $(targetTable + ' tr');
}
Error: Uncaught Error: Syntax error, unrecognized expression: [object Object].tr
I think the problem is here:
sortTable($('#myTable'));
You're passing targetTable a jQuery object, so adding it to a string forces it to turn into a string, which is [object Object]. I think you mean:
sortTable('#myTable');
function sortTable(targetTableSelector) {
var rows = $(targetTableSelector+ ' tr');
}
You can use .find():
var rows = targetTable.find("tr");
That will find all the <tr> elements starting from the table and give you a new jQuery object containing them.
You can get the selector that was used to construct a jQuery object:
var tableSelector = targetTable.selector;
In this case that'd be the string "#myTable". However, jQuery objects are not always formed from selectors. If you obtain a reference to the table DOM node via something like an event handler, there won't be a selector. You can still use .find() to locate elements from a "starting point" jQuery object.
Note that .find() does its work for all the elements in the starting jQuery collection. If your initial object was a collection including two <table> elements, then .find("tr") would find all the rows under both tables.
Method one, passing jQuery object:
sortTable($('#myTable'));
function sortTable(table) {
var rows = table.find('> tbody > tr');
}
Method two, passing selector string:
sortTable('#myTable');
function sortTable(tableSelector) {
var rows = $(tableSelector).find('> tbody > tr');
}
Edit: (assuming you want only the rows within the tbody and not the head, otherwise remove "> tbody > tr")
Your passing in a jQuery object. Not the id. This means that when you concatenate your id to your targetTable argument you'll get:
[object Object] tr
Thus you'll be trying to select:
$("[object Object] tr")
Which isn't what you want. Instead, you need to pass in the table id into your function so that you concatenate it with a string, rather than an object.
See working example below:
function sortTable(targetTable) {
var rows = $(targetTable + ' tr').toArray();
return rows.toArray();
}
console.log(sortTable('#myTable'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" border=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Bob</td>
<td>23</td>
</tr>
<tr>
<td>John</td>
<td>33</td>
</tr>
</table>

How to automaticaly add an incrementing numeric id for each td elements in javascript

I want javascript to automatically add an incrementing numeric id for each of my td elements.
I want a script at the bottom of each HTML page to tell what first id will be input for that page and ++ automaticaly for each next td element. I tried a lot of things with for loop and something is missing with my appendChild method, i just can't make it work but i know i'm almost there.
If someone could give a hand, it would be greatly appreciated!
Here is how a manually enter those IDs each new month :
<tr>
<td id="603" class="offweekend"></td>
<td id="604" class="offmonth"></td>
<td id="605" class="offmonth"></td>
<td id="606" class="offmonth"></td>
<td id="607" class="offmonth"></td>
<td id="608" class="offmonth"></td>
<td id="609" class="weekend">1</td>
</tr>
<script>
tds = document.getElementsByTagName("td");
tdlength = tds.length;
firsttd = 603;
lasttd = firsttd + tdlength;
for (i = firsttd; i < lasttd; i++){
td.appendChild() //???That's where i'm confused, i'm i wrong
with this approach?
}
</script>
//Thank you, i'm still learning :)
Assuming that you have a variable firstValue that stores what the id of the first td should be, you can use this:
document.querySelectorAll("td").forEach((v,i)=>v.id=i+firstValue);
The querySelectorAll grabs all of the td elements in order as a NodeList.
v is the td element and i is the position of the element in the array
You don't need to use appendChild. You can simply iterate through the cells and set the id immediately.
let id = 603;
const cells = document.querySelectorAll('td');
cells.forEach(function(el) {
el.id = id++;
});
A small aside: I don't know your indended use but you might be better off using a data attribute for storing this information instead.
let id = 603;
const cells = document.querySelectorAll('td');
cells.forEach(function(el) {
el.setAttribute('data-id', id++);
});

Use javascript to Transfer Text

I have got 3 tables in html that at a certain time, i want to move text from 1 table will move to another. Can someone show me a javascript function ( just a few lines long - don't spend too long) that can transfer text from one td to another.
Transferring ONE td value to another:
Well if you assign a td an ID (ex. "firstTD", "secondTD"), you could store it's value in a variable (ex. "tdToMove"):
var tdToMove = document.getElementById("firstTD").innerHTML;
document.getElementById("secondTD").innerHTML = tdToMove;
Note: This will only copy the innerHTML of a single td, and duplicate it on the other. If you wish to clear the first entry, run:
document.getElementById("firstTD").innerHTML = "";
to render the first td 'blank'.
You will have to experiment to find a way to move ALL values to the other table, this was just a pointer.
Also, If the text is moving from table to table, and the tables remain identical, why not just place the input in both to begin with, OR, simply run a code to duplicate the table when you would like to move the data?
You can use Node.textContent property to get and set the text of a Node.
Here is a link about it:https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
I have made a fiddle to show you that in action: https://jsfiddle.net/3dep0msg/
In this fiddle i transfer the text of cell1 to cell2 and add it to the text of cell2.
I use textContent and not innerHTML property, because you wanted to transfer ONLY text!
function copyTextFromCell(id1,id2){
var cell1= document.getElementById(id1);
var cell2= document.getElementById(id2);
cell2.textContent = cell2.textContent+cell1.textContent;
}
copyTextFromCell("cell1","cell2");
if you want to do this using jquery.
<table id="table1">
<tr>
<td>1,1</td>
<td>1,2</td>
</tr>
<tr>
<td>2,1</td>
<td>2,2</td>
</tr>
</table>
<table id="table2">
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
$('#table1 tr').each(function (indexR, element) {
$(this).find('td').each(function (index, element) {
var table2Rows = $('#table2 tr');
var table2Row = table2Rows.eq(indexR);
var table2Column = table2Row.find('td');
var table2cell = table2Column.eq(index);
table2cell.html( $(this).html());
});
});
working fiddle.

Jquery next() is not working

I have
<table class="prodtable">
<tr>
<td></td>
<td>
<input class="editok" value="2" />
</td>
<td>
<input name="prodnumber" value="1" />
<i></i>
</td>
</tr>
</table>
and this js
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
$(this).parent('td').text(neuanzahl);//<-- till here works fine
$(this).parent('td').next().find('input').val(neuanzahl);//<-- from here, failure
$(this).parent('td').next().find('i').addClass('icon-pencil');
});
the editok input was inserted dynamically, thats why i am setting the handler from parent table.
my problem is, on blur event, the value of the given input should be put in the next input which is inside the next td with name prodnumger and the <i> should get the class icon-pencil.
I am trying for 1 hour now, what a shame.. not a single success. what am I doing wrong here?
This line
$(this).parent('td').text(neuanzahl);
replaces everything in the TD, as that's what text() does, it overwrites everything, so on the next line when you do
$(this).parent('td').next().find('input') ...
there is no this, you just removed it with text()
Just chaining instead of using multiple lines will keep the reference
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = this.value;
$(this).parent('td')
.text(neuanzahl)
.next('td')
.find('input')
.val(neuanzahl)
.next('i')
.addClass('icon-pencil');
});
FIDDLE
The minute you call $(this).parent('td').text(...), you've removed the input from its parent. So $(this).parent('td') in the following calls won't match anything.
Save that td at the start, and use it throughout:
$('.prodtable').on('blur','.editok',function(){
var neuanzahl = $(this).val();
var td = $(this).parent('td');
td.text(neuanzahl);
td.next().find('input').val(neuanzahl);
td.next().find('i').addClass('icon-pencil');
});
Example: http://codepen.io/paulroub/pen/xHwdi
Solution is to store reference of next div in a variable.
$('.prodtable').on('blur', '.editok', function () {
var td = $(this).parent('td');
var next = $(this).parent('td').next(); //Store reference of next div in a variable
var neuanzahl = $(this).val();
td.text(neuanzahl);
next.find('input').val(neuanzahl);
next.find('i').addClass('icon-pencil');
});
Problem with your code is that when $(this).parent('td').text(neuanzahl) reference to this is lost as you have replaced the content to td.
Your table opening tag is not spelled correctly that is likely why you are having difficulties.

Is it possible to get the value of a <td> element using onclick?

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')

Categories

Resources