get the content of the prev element jquery - javascript

I have this structure into my html.
<table border="1" cellpadding="1" cellspacing="2">
<thead>
<tr>
<th>Name</th><th>Age</th><th>Address</th><th>Option</th>
</tr>
</thead>
<tbody>
<tr>
<td>here is the name</td>
<td>here is the age</td>
<td>here is the address</td>
<td><button class="update">update</button></td>
</tr>
<tr>
<td>here is the name2</td>
<td>here is the age2</td>
<td>here is the address2</td>
<td><button class="update">update2</button></td>
</tr>
</tbody>
</table>
as you can see from the above structure, the display will be this.
table header = Name, Age, Address, Option.
table body = here is the name, here is the age, here is the address, button update
table body = here is the name2, here is the age2, here is the address2, button update2
now what Im trying to do is when I click the update button, i must able get the content of the address td to name td at the single same row and each must be stored in a specified variable e.g. ($name, $age, $address). assume i have mutiple row, I must able to retrieve only the content of address td to name td of the same row. To be more precise, as the structure above, I must able to get the 'here is the name', 'here is the age', 'here is the address' and put each in a specified variable e.g. ($name, $age, $address) when I click the u"update" button and not the "update2" button.
so far what I tried is.
$('.update').click(function(){
$address = $(this).prev('td').content();
alert ($dateposted);
});
but seems not returning anything. Any help would be greatly appreciated. Thank you!

Here this is the button, which does not have a previous sibling, the td you are looking for is the previous sibling of the td parent of the clicked button, also you have to use .text()/.html() to get the contents
$address = $(this).parent().prev('td').text();//$(this).closest('td')

Here is another way to do it. After you get all the previous divs then loop them to set the value to the correct variable.
$('.update').click(function () {
var contents = $(this).parent().prevAll('td');
var name;
var age;
var address;
for(i = 0; i<contents.length; i++){
var currentContent = $(contents[i]);
switch(i){
case 0:
name = currentContent.text();
break;
case 1:
age = currentContent.text();
break;
case 2:
address = currentContent.text();
break;
}
}
console.log(address, age, name);
});
For working example, please refer to http://jsfiddle.net/zeskysee/72j1oaqb/4/
Hope this help :)

Related

JavaScript must search td for string with 'http' and convert it to link that opens in new tab when clicked

I have a table in my html that is populated dynamically from a JSON file. Once the page loads and the table is populated, some columns contain strings that are urls. I had a script that was able to search the table and assign a class to any string that started with 'http'.
I am trying to rework that script so that it will search the table (td cells), find the strings that start with 'http', convert them to hyperlinks and open the url on a new tab (_blank). But, it is not working. Can someone point out where I'm going wrong in the script below? I know there is the link() method but it is depreciated so I don't want to use it.
The table is identified by ID (#YukonTerr_FR) in the script.
Thanks!
var tds4 = document.querySelectorAll("#YukonTerr_FR td");
for (var i = 0; i < tds4.length; i++) {
var str4 = tds4[i].innerText;
var link = document.createElement("a");
if (str4.includes("https")) {
link.setAttribute("href", "str4");
link.setAttribute("target", "_blank");
link.appendChild(document.createTextNode("str4"));
}
}
You need to clear the content of the td and append the newly created "a" element to the td. Also, use the variable str4, not the string "str4"
var tds4 = document.querySelectorAll("#YukonTerr_FR td");
for (var i = 0; i < tds4.length; i++) {
var str4 = tds4[i].innerText;
var link = document.createElement("a");
if (str4.includes("https")) {
tds4[i].innerText = ""; //Clear content of td
link.setAttribute("href", str4);
link.setAttribute("target", "_blank");
link.appendChild(document.createTextNode(str4));
tds4[i].appendChild(link); // Add the new link to td
}
}
<b>Before:</b>
<table>
<tr>
<td>https://www.google.com</td>
</tr>
<tr>
<td>Just a string</td>
</tr>
<tr>
<td>https://amazon.com</td>
</tr>
</table>
<p></p>
<b>After:</b>
<table id="YukonTerr_FR">
<tr>
<td>https://www.google.com</td>
</tr>
<tr>
<td>Google</td>
</tr>
<tr>
<td>https://amazon.com</td>
</tr>
</table>
Your code doesn't appear to have any obvious errors, but I can't see where you're adding it back to the table. Something like:
...
tds4[i].appendChild(link)

jQuery: Cannot access text box value using .val()

I'm building a dynamic table that users can add to, delete from, or edit. I have the following:
$(document).on('click', '.edit_rule', function() {
// editable text boxes for name and description
$(this).closest("tr").find("td:nth-child(2), td:nth-child(3)").each(function() {
var html = $(this).html();
var input = $('<input type="text" />');
input.val(html);
$(this).html(input);
});
// replace Edit and Delete with Save and Cancel
$(".edit_rule").replaceWith("<input id='Button' type='button' value='Save' class='sav$
$(".delete_rule").replaceWith("<input id='Button' type='button' value='Cancel' class=$
});
Which all works fine. But, when I try to access the new values in the next boxes, the value comes up blank. I was trying to use .val() and now am trying .text() as follows:
$(document).on('click', '.save_edit', function() {
var $row = $(this).closest("tr");
var $name = $row.find("td:nth-child(2)").find('input');
console.log($name.text()); // prints empty string
});
I'm fairly new to Javascript, so is there some weird scope thing I'm not understanding that prevents the value from being accessed in a separate function? Is there another way to do it?
EDIT: Here is the corresponding HTML
<div id="customperms_table_container" style="height:655px;">
<table id="customperms_table_form" cellpadding="10" cellspacing="$
<caption></caption>
<thead>
<tr>
<th>#</th>
<th>Role Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Issue is td has no value.
Solution is use .text() or .html() to get its text or html
Based on comment:
Your selector should be:
var $name = $row.find("td:nth-child(2)").find('input')// add class or id if there other inputs
Sorry about broken html, but combo of guradio and Haze fixed it.
var $name = $row.find("td:nth-child(3)");
console.log($name.val()); // <-- prints correct value

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.

get dynamic rows data values to prefill the forms using javascript

I have a table in which the rows are dynamic and the values come from database.
for eg my table is as follows:-
name|email
xyz|xyz#gmail.com
pqr|pqr#gmail.com
I have kept the names as link on clicking of which a form opens below with the same field as of table i.e
name:----
email: ----
so now what i want is with opening of the form i also want that the form should get prefilled with values that are there in table ..
for eg:- if a user clicks pqr then a form should get opend with values in it..
name : pqr
email : pqr#gmail.com
I made a javascript function where i pass the userid of the username that the user clicks..and in that i function i did the following :
var id=userid;
var row = document.getElementById(id);
var inputs = row.getElementsByTagName("td");
document.getElementById("fname").value = inputs[0].innerHTML;
document.getElementById("email").value = inputs[1].innerHTML;
and as i am using
inputs[0].innerHTML;
it prints the name like this :
<font size="4">xyz</font>
but I want only 'xyz' in my textbox..for that when I did :
inputs[0].value;
it gave me its value as undefined...why is it so?
please someone guide on getting the form filled with values of the row.
I'm making a few assumptions here. See this fiddle for working code: http://jsfiddle.net/G6Q5X/
Here's a basic table.
<table id="list">
<tr>
<td>Name 1</td>
<td>Email 1</td>
</tr>
<tr>
<td>Name 2</td>
<td>Email 2</td>
</tr>
</table>
First you want to get the table by ID and get the rows that it contains:
//nodeList of all rows in the table
var table = document.getElementById('list').children[0].children;
Then add an event listener to each link:
for(var i=0, len=table.length; i<len; i++){
var link = table[i].children[0].children[0];
link.addEventListener('click', getInfo);
}
The callback for the event listener will call a function, I used one I called "getInfo":
var getInfo = function(){
var name = this.innerHTML;
var email = this.parentNode.parentNode.children[1].innerHTML;
alert('Your name is: ' + name + ' and email is: ' + email)
}
I hope this helps.

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