Reversing first and last names using jquery - javascript

Trying to take this table and take the names, when I click one radio button it changes the names from something like: Tom Hanks to Hanks, Tom. Here is the html:
<h1>Address Book</h1>
Show Names as:
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbod
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Interview Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise</td>
</tr>
</tbody>
</table>
</div>
Here is the jquery, its all I could come up with and does not work at all. :(
$(document).ready(function () {
$("input[name='change_last_first']").click(function () {
$(".name").text(function() {
$(this).split(" ").reverse();
});
});
});
});

You need to return the result. Also since you are using the function arg syntax of text use the second argument of the function for the current text.
$(".name").text(function(_, cur) {
return curText.split(/\s+|,/).reverse();
});
Fiddle
Another easy way to handle this assuming the general format of name is First Last or Last, First:
$("input[name='change_last_first']").change(function () {
var arr = [" ", ","],
sep = this.value === 'first' ? 0 : 1;
$(".name").text(function (_, curText) {
return curText.split(arr[sep % 2]).reverse().join(arr[(sep + 1) % 2]);
});
});
Demo

For this you need to split full name with space and than you can use reverse().
Note: because reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string.
$("input[name='change_last_first']").click(function () {
$(".name").each(function() {
var revName = $(this).text().split(" ").reverse().join(" ");
$(this).text(revName);
});
});
Try This

Related

Get text from HTML Table and place it in a pre-defined string

How can I get the value of the first TD and place it in a pre-defined string in jquery?
My try:
$('td:first-child').each(function() {
console.log($(this).text());
});
How can I put the value now in the following string as parameter and maybe remove the white spaces and add the dot between?
String: {{email_open::john.sample#mymail.com}}John Sample{{email_close}}
I thought I need the wrap Function in Jquery or am I wrong?
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Sample</td>
</tr>
</tbody>
</table>
You can use something like toLowerCase() and trim() to remove space and lower the text:
var namemerge= $(this).text().toLowerCase().trim();
to replace the space in between word you can use regex like suggested in this answer and append the mail suffix:
namemerge= namemerge.replace(/ /g, '.')+'#mymail.com';
$('td:first-child').each(function() {
console.log($(this).text());
var namemerge= $(this).text().toLowerCase().trim();
console.log(namemerge);
namemerge= namemerge.replace(/ /g, '.')+'#mymail.com';
console.log(namemerge);
});
// I believe you can continue from this
console.log('{{email_open::john.sample#mymail.com}}John Sample{{email_close}}');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Sample</td>
</tr>
</table>

Editing form by double clicking element

I have a form, and I want to be able to edit any part of that form by double clicking it. So going from this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
How can I by double-clicking an element, transform it to an input element?
For example: if I double click on John Smith, the HTML changes into this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<form action="index.php" method="post">
<td><input type="text" value="John Smith" name="name" /></td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</form>
</tr>
</table>
So now I can change John's name.
Does someone know how to do it?
Try this, fields from the second row are editable with dblclick
document.querySelectorAll("table tr:nth-child(2) td").forEach(function(node){
node.ondblclick=function(){
var val=this.innerHTML;
var input=document.createElement("input");
input.value=val;
input.onblur=function(){
var val=this.value;
this.parentNode.innerHTML=val;
}
this.innerHTML="";
this.appendChild(input);
input.focus();
}
});
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
How about that:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td id="name">John Smith</td>
<td>johnsmith#gmail.com</td>
<td>+12345678</td>
</tr>
</table>
<script>
$("#name").dblclick(function(e) {
if (e.target.parentElement.nodeName != 'form') {
var form = $('<form action="index.php" method="post">');
var parent = $(e.target.parentElement);
parent.children().each(function(i, elem){
form.append(elem);
})
parent.empty();
parent.append(form);
}
})
</script>
It handles double click event and wraps all <td> elements inside <tr> into <form> tag.
I believe this will do what you want:
$("document").ready(function () {
var haveForm = false;
$("td").dblclick(function () {
var thisVal = $(this).html();
if (!haveForm) {
$("td").wrapAll('<form action="index.php" method="post" />');
haveForm = true;
}
$(this).html('<input type="text" value="' + thisVal + '" name="name" />');
});
});
jsFiddle
This makes use of jQuery's wrapAll() and safe guards against multiple form elements being created.

How to iterate through each data in a table

<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
I am a bit confused about how to get all the data from the table using a single button. When the user click on the button i should get all the table data. I tried with the below code. I need to get all the data in a array format. So that i can save all the data to my database.
$("#saveButton").click(function(event) {
var table = document.getElementById("table");
var dataArray = [];
var data = table.find('td');
for (var i = 0; i <= data.size() - 1; i = i + 4) {
data.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
});
Try this code.
$("#saveButton").click(function(event) {
var data = [];
$("#table tr").each(function(i){
if(i != 0){
data.push({
id: $(this).find("td:eq(0)").html(),
name: $(this).find("td:eq(1)").html(),
email: $(this).find("td:eq(2)").html(),
phone: $(this).find("td:eq(3)")}).html()
});
}
});
//do something with data
});
If you want to use jquery, have a look at https://jsfiddle.net/qg6xpy39/
HTML:
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button id="saveButton">
click
</button>
JS:
$("#saveButton").click(function(event) {
var rows = $('#table td'); // retrieve the rows of your table
var dataArray = [];
$.each(rows, function(idx, elt) {
dataArray.push($(elt).text()); // add cell text content to the data array
});
console.log(dataArray); // so you can check what's in the array ;-)
});
As said in comments, in plain JavaScirpt.
use querySelectorAll to select all trs. Then iterate in each of them and get it's td's innerHTML and push it in an array.
Then use Array.shift() to remove the th elements. That is, the titles.
The code
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
Check the below snippet.
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button onclick="save();">Save</button>
Another possible approach, again using pure javascript rather than jQuery would be to use the DOM NodeIterator in conjunction with an XPath via Document.evaluate()
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Javascript DOM Processing</title>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(e){
var query='/html/body/table[#id="table"]/tbody/tr/td';
var xpr = document.evaluate( query, document, null, XPathResult.ANY_TYPE, null );
var td = xpr.iterateNext();
var dataTbl=[];
while( td ){
try{
dataTbl.push( td.textContent );
td=xpr.iterateNext();
}catch( err ){
alert( 'Error'+err );
}
}
/* The data from all table cells is now in the array */
alert( dataTbl.join(String.fromCharCode(10)) );
},false);
</script>
</head>
<body>
<!-- content -->
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
</body>
</html>
Simplest approach would be
var data_arr = [];
$('#table tr').each(function() {
data_arr.push(this.cells[0].innerHTML);
data_arr.push(this.cells[1].innerHTML);
data_arr.push(this.cells[2].innerHTML);
data_arr.push(this.cells[3].innerHTML);
});

nested ng-repeat with open particular index with respect to repeated data

Every time the toggle is clicked, all payments are getting replaced with new payments. My problem is how to maintain the payments of a particular index of every click and show at respective index. please help me out
here is my html
<tbody data-ng-repeat="invoice in relatedInvoices>
<tr>
<td class="td-bottom-border">
{{invoice.PayableCurrencyCode}} {{invoice.PayablePaidAmount | number: 2}}<br />
<small>
<a data-ng-click="isOpenPayablePayments[$index] = !isOpenPayablePayments[$index]; togglePayablePayments(invoice.PayableInvoiceId)">Paid</a>
</small>
</td>
</tr>
<tr data-ng-show="isOpenPayablePayments[$index]">
<td>
<table>
<thead>
<tr>
<th>Transaction Id</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="payment in payablePayments">
<td>{{payment.TransactionId}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
Here is my javascript
var getPayments = function (invoiceId) {
paymentService.getPayments(invoiceId).then(function (paymentsResponse) {
return paymentsResponse.data;
});
};
$scope.togglePayablePayments = function(invoiceId) {
$scope.payablePayments = getPayments(invoiceId);
};
If I understood correctly, you want to have "payablePayments" for every invoice.
This is working: http://plnkr.co/edit/cj3jxZ?p=info
Try something like
// init at beginning
$scope.payablePayments = [];
$scope.togglePayablePayments = function(invoiceId) {
$scope.payablePayments[invoiceId] = getPayments(invoiceId);
};
and then
<tr data-ng-repeat="payment in payablePayments[invoice.PayableInvoiceId]">
Otherwise you overwrite the object for the preceding invoice.

Merging javascript objects into HTML table

I have two javascript objects, the contents of which came from these two HTML tables.
Each pre-merge table now has it's own object. The object is structured as follows:
The first array element within the object contains the column headers from the pre-merge tables, and the array elements following that contain the <tr> data from each table.
Is it possible to merge these two objects together to produce one HTML table? As you can see the in the pre-merge tables the x-value is shared between both, meaning it is common between the two objects too. I thought there may be a way of comparing these values, and then populating the table, but I'm not sure how.
I would like the merged table to look like the following:
x-value: common dates shared between objects
columns: data from each of the pre-merge tables with their headers
Here is my code (you can also see it on this CodePenHere):
$(document).ready(function(){
gatherData();
results();
});
function gatherData(){
data = [];
tables = $('.before').find('table');
$(tables).each(function(index){
table = [];
var headers = $(this).find('tr:first');
var headerText = [];
headerText.push($(headers).find('td:nth-child(1)').text());
headerText.push($(headers).find('td:nth-child(2)').text());
table.push(headerText)
$(this).find('tr').each(function(index){
var rowContent = [];
if (index != 0){
$(this).find('td').each(function(index){
rowContent.push($(this).text());
})
}
table.push(rowContent)
})
data.push({table: table})
});
console.log(data)
}
function results(){
var results = $('.after1').find('thead');
$(results).append("<th>" + data[0].table[0][0] + "</th>");
for (i in data){
$(results).append("<th>" + data[i].table[0][1] + "</th>");
var b = data[i].table.length;
for (a = 2; a < b; a++){
console.log(data[i].table[a][0] + " || " + data[i].table[a][1])
}
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
<h1 class="page-header">Formatter.js</h1>
</div>
<div class="container before">
<h3>Before</h3>
<table border=1 cellspacing=0 cellpadding=0 alignment="" class="a" id="3">
<tbody>
<tr>
<td>x-value</td>
<td>Operational Planned</td>
</tr>
<tr>
<td>09/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>10/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>11/11/2015</td>
<td>66358</td>
</tr>
<tr>
<td>12/11/2015</td>
<td>65990</td>
</tr>
<tr>
<td>13/11/2015</td>
<td>55993</td>
</tr>
<tr>
<td>14/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>15/11/2015</td>
<td>0</td>
</tr>
</tbody>
</table>
<table border=1 cellspacing=0 cellpadding=0 alignment="" class="a" id="3">
<tbody>
<tr>
<td>x-value</td>
<td>Something Else</td>
</tr>
<tr>
<td>09/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>10/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>11/11/2015</td>
<td>2552</td>
</tr>
<tr>
<td>12/11/2015</td>
<td>86234</td>
</tr>
<tr>
<td>13/11/2015</td>
<td>33623</td>
</tr>
<tr>
<td>14/11/2015</td>
<td>0</td>
</tr>
<tr>
<td>15/11/2015</td>
<td>0</td>
</tr>
</tbody>
</table>
<hr>
</div>
<div class="container after">
<h3>After</h3>
<table class="table after1">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
As I understand your issue, you want to merge the tables by the key values in coloumn x-value.
Here is how I would do it:
Collect data from each table into a dictionary with coloumn x-value as key
Save values for each key as array.
The main part is collecting the data in the dictionary. Here is the part:
var table = {
header: [],
data: {}
};
$(this).find('tr').each(function(index) {
// ignore first row
if (index === 0) return true;
// read all data for row
var rowData = [];
$(this).find('td').each(function() {
var value = $(this).text();
rowData.push(value);
});
// key value for dictionery
var key = rowData[0];
// add value to array in dictionary if existing or create array
if(table.data[key]) {
table.data[key].push(rowData[1]);
} else {
table.data[key] = [rowData[1]];
}
});
By using a simple javascript object as a dictionary we create properties on the fly, just like a dictionary.
See the plunker for the full script. I've written comments on the different parts to make the functionality clear. Let me know if anything is unclear.
As a note on your code. You can use multiple arguments in the jQuery selector to make your selections simpler, so this (see note below)
tables = $('.before').find('table');
can become this:
tables = $('.before table');
Edit
As noted by Mark Schultheiss in the comments, the later, but shorter syntax for jQuery selectors can be slower than the first one on large DOMs. So use the extended syntax on large DOMs. I've updated the plunker to use the better performing syntax.

Categories

Resources