I'm using jquery, as well as the CSVtoTable (plugin here: https://code.google.com/p/jquerycsvtotable/ ) plugin to convert large CSV files into tables that I can manipulate. I need to attach links relevant to each row.
I need to convert the text in one of these rows to add a link to a pdf. The problem is I can't seem to modify the strings. I'm using data like that found here: http://jsfiddle.net/bstrunk/vaCuY/297/
The file names generated by my system can't be easily edited, so I'm stuck using these formats:
423-1.pdf
So I need to convert two strings from tables formatted like so:
4/23/2013
1
to drop the year, as well as the slashes, and add a '-' and then the extra digit.
I'm able to grab the table data, I just can't seem to manipulate the variables with either the .replace or .substr
$(document).ready(function () {
$("tr td:nth-child(5)").each(function () {
var $docket = $('td=eq(5)');
var $td = $(this);
var $dataDate = $td.substr(0, $td.lastIndexOf("/"));
var $newDataDate = $dataDate.replace("/", "");
$td.html('<a html="./docs/' + $newDataDate.text() + '-' + $docket.text() + '.pdf">' + $td.text() + '</a>');
});
});
(edit): Sample table data:
<tr><td>13CI401111</td><td>22</td><td>Name1</td><td>Name2</td><td>4/23/2013</td><td>1</td></tr>
<tr><td>13CI401112</td><td>22</td><td>Name1</td><td>Name2</td><td>4/24/2013</td><td>2</td></tr>
First set the table id properly:
<table id="CSVTable">
Then use the right selector to select the 5th cell in each row:
$("#CSVTable tr td:nth-child(5)") //note that we need to tell Jquery to look for the cells inside `CSVTable` otherwise it will search the whole document
dollar sign is not required at the beginning of each variable and doesn't have any significance, you can remove it.
This wont work:
var $docket = $('td=eq(5)');
it's telling jquery to look for 6th cell but where? you should specify the parent like:
$("#CSVTable tr td:nth-child(6)");
but we only need the next cell to the one already selected in each function, so a better approach would be to use next() method which will select the next td directly:
$(this).next('td');
complete code:
$(document).ready(function () {
$("#CSVTable tr td:nth-child(5)").each(function () {
var td = $(this),
docket = td.next('td').text(),
dataDate = td.text(),
newDate = dataDate.substr(0, dataDate.lastIndexOf('/')).replace("/", '');
td.html('' + dataDate + '');
});
});
Demo
Bstrunk, try this :
$(function() {
$("tr").each(function () {
var $tr = $(this);
var $td_date = $tr.find('td').eq(4);
var $td_docket = $tr.find('td').eq(5);
var dateArr = $td_date.text().split("/");
$td_date.html('<a html="./docs/' + dateArr[0] + dateArr[1] + '-' + $td_docket.text() + '.pdf">' + $td_date.text() + '</a>');
});
});
Related
As the code below shows, I am appending a table with some table rows containing table data. The table data is getting appended with excel formula inside. How can I change the count variable inside td.class after it was appended in table upon click event or something similar.
I Want to update td.excel count attribute with onclick event
.append("<td class="
excel " x:num x:fmla=\"=SUM(H" + count + " *I" + count + ")
$("#example").on("click", "button", function() {
$(this).closest("tr").remove();
count--;
var i = 10;
for (i = 10; i < count; i++) {
let div1 = document.getElementsByClassName("excel");
var attribute = div1.SetAttribute(count, count);
}
}
Your problem is not clear. But what I've got from your question is that you want to dynamically append to . But you end up with excel formula getting inside it.
So, according to me when you want to insert something dynamically then you should use `` these quotes instead of '' and "". eg :-
var i = 1;
.append(`<td class="hello${i}"></td>`)
I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript
The code I generate this with:
friendListInDiv = document.createElement("p");
var link = document.createElement("a");
link.onclick = function() {
openChat(friendsXML[i].textContent)
};
var friendText = document
.createTextNode(friendsXML[i].textContent + ":"
+ statusXML[i].textContent);
link.appendChild(friendText);
friendListInDiv.appendChild(link);
friendDiv.appendChild(friendListInDiv);
Now the problem I'm facing I have demonstrated in a jsfiddle:
https://jsfiddle.net/x897pv9o/
As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"
This is because these tags
<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>
are not being formatted correctly, how can I make them format correctly?
As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.
In document.createTextNode:
var friendText = document.createTextNode(
friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);
In $('#searchinfriend').keyup:
$('#searchinfriend').keyup(function () {
var valThis = $(this).val().toLowerCase();
$('#friendlist p a').each(function () {
var text = $(this).text().trim().toLowerCase();
(text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
});
});
This is almost working but I am missing something. I am building an html table and I have JQuery. The idea is fairly simple. I have a list of names which will populate the first column of the table body. Next come two blank columns for some book keeping then a number of columns based on the number of days in the month of the date value passed into the function then a final bookkeeping column.
The general table structure is fine, the header and colgroups are fine. The thing that is biting me is the section of <td></td>'s in each body row that correspond the the days of the month. They are not showing up in the resulting table.
There are two loops. The first one builds the elements necessary to display the month day columns for the colgroup, header and body rows. Again, the colgroup and header bits are working. The $trb portion builds a single "row" of blank td elements that I hope to insert into each body row. The problem is $trb is not being appended/inserted to the body rows.
I'm not seeing this, ideas?
$(function() {
var list = ['11111 111', '2222 22222222', '3333333, 3333 3333333'];
buildMonthTable(new Date(), list);
function buildMonthTable(targetDate, list) {
var myDate = new Date(targetDate.getTime());
myDate.setDate(1);
myDate.setHours(0);
myDate.setMinutes(0);
myDate.setSeconds(0);
var lastDay = new Date(myDate.getTime());
var dayNames = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
var $table = $('<table>');
var $colGroup = $('<colgroup>');
var $thead = $('<thead>');
var $tbody = $('<tbody>');
var $trh = $('<tr>');
var $trb = $('<tr>');
$trh.append('<th>Name</th>');
$colGroup.append('<col class="colPlain colName"/>');
$trh.append('<th>Last Date</th>');
$colGroup.append('<col class="colPlain colRank"/>');
$trh.append('<th>Month Total</th>');
$colGroup.append('<col class="colPlain colTestDays"/>');
for (lastDay = new Date(myDate.getTime());
lastDay.getMonth() == myDate.getMonth();
lastDay.setTime(lastDay.getTime() + 86400000)) {
$trh.append('<th>' + lastDay.getDate() + '<br/>'
+ dayNames[lastDay.getDay()] + '</th>');
if (lastDay.getDay() % 2 == 0) {
$colGroup.append('<col class="colPlain colDay"/>');
} else {
$colGroup.append('<col class="colShade colDay"/>');
}
$trb.append('<td> </td>');
}
$trh.append('<th>Practice Days This Month</th>');
$colGroup.append('<col class="colPlain colTestDays"/>');
$table.append($colGroup);
$thead.append($trh);
$table.append($thead);
for (var i = 0; i <list.length; i++) {
var $bodyRow = $('<tr></tr>');
$bodyRow.append('<td>' + list[i]
+ '</td><td> </td><td> </td>');
console.log($trb);
$bodyRow.append($trb); // <===== this is not appending
$bodyRow.append('<td> </td>');
$tbody.append($bodyRow);
}
$table.append($tbody);
$("#content").append($table);
}
});
rafaelcastrocouto is correct, it is outputting... so I think you're problem is here:
var $bodyRow = $('<tr></tr>');
You want to have the tr tag at the top and close the tr at the bottom instead.
Also, I don't see your closing table tag either.
The trb is appending as you can see here
$trb.append($('<p>x</p>')); // this will make you see lots of "x" in your table
$bodyRow.append($trb); // <===== so this is appending
You should not append a tr(trb) inside another tr(bodyRow) the way you are doing and I guess you do not really want to do that rigth?!
I've a form in which containing one <div> tag and the HTML within it. This is what I've when page loads. Then through AJAX I'm appending the same block(i.e. ) to the existing one. In every <div> tag there is one <table> and in that <table> I've a button with class products. After clicking on it I'm calculating the no. of rows present in that table only and assigning the id to the newly added row. But the issue I'm facing is when I add multiple such tables using AJAX and click on add button of any table it's calculating the total no. of rows present in all tables and adding that much no. of rows to the table in which I clicked add button. This shouldn't have to happen. It has to add only one row. I've created a jsfiddle for your reference. In fiddle I've put in static HTMl so it's working fine over there but on my local machine when I add multiple tables using AJAX I'm getting wrong no. of rows added.For example if I added three tables and click on add button of first table then it's adding four rows to that table. Why it's counting the total no. of rows present in all the tables present on a page?Is there any need to improve my script? My script is as follows:
$(document).ready(function() {
$('.products').click(function () {
var table_id = $(this).closest('table').attr('id');
var no = table_id.match(/\d+/)[0];
//var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
var tbody = $('tbody', '#'+table_id);
var n = $('tr', tbody).length + 1;
new_row.attr('id', 'reb' + no +'_'+ n);
$(':input', new_row).not('.prod_list').remove();
$('select', new_row).attr('name','product_id_'+no+'['+n+']');
$('select', new_row).attr('id','product_id_'+no+'_'+n);
$('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">×</button>').appendTo( $(new_row.find('td:first')) );
tbody.append(new_row);
$('.delete').on('click', deleteRow);
});
});
Following is jsFiddle link: http://jsfiddle.net/vrNAL/2/
I think what you mean to query is this:
var tbody = $('#' + table_id + ' tbody');
Instead of:
var tbody = $('tbody', '#' + table_id);
From the jQuery documentation, I don't think selectors work this way.
You are doing some strange things with the IDs here. why are you getting the IDs and selecting the sleemts with that, instead of using the selected elements directly?
Example:
var table_id = $(this).closest('table').attr('id');
var table = $("#" + table_id);
Is the same as just
var table = $(this).closest('table');
and
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
is the same as:
var new_row = table.find('tbody tr:first').clone();
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.