How to short this code or this true code? - javascript

I need in table change td when i click the button. I'm begginner in Jquery. I think to use this document.createTextNode In order to change the code in the table
.
Since I am a beginner, this will be correct or some differently correctly. Because table is so long and too code more
It's Example many code in Jquery (Screnshot)
$(".price-btn_1").click(function() {
$( "td:eq(2)").empty().append(document.createTextNode("123") );
$( "td:eq(3)").empty().append(document.createTextNode("456") );
});
> when .price-btn_2 click change text in table td
$(".price-btn_2").click(function() {
$( "td:eq(2)").empty().append(document.createTextNode("50") );
$( "td:eq(3)").empty().append(document.createTextNode("30") )
});
.price-table tr td{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="price-btn_all price-btn_1 active">iPhone 4</button>
<button class="price-btn_all price-btn_2">iPhone 4s</button>
<table class="price-table">
<thead>
<tr>
<td>bla1</td>
<td>bla2</td>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>456</td>
</tr>
</tbody>
</table>
Thanks!

With jQuery it is way more easy to accomplish your goal. Since you only want to set the text in the table cells, just use text("123") on the selection:
$("td:eq(2)").text("123");
http://api.jquery.com/text/
I must say that getting the tds just by their number in the document order is no good design. What if you decide to add another table before the first one? You would have to adjust all the numbers in your source code. Better use ids instead.

Concept:
Store your texts in a 2-dimensional array (2d array)
Loop through each td and set their text according to the index
// keep the texts here
var data = [
['table0#data0', 'table0#data1', 'table0#data2', 'table0#data3'],
['table1#data0', 'table1#data1', 'table1#data2', 'table1#data3'],
];
$(".price-btn_1").click(function() {
// loop through each <td>
$(".price-table tbody td").each(function(n, el){
// data[0] means table1
// data[0][n] means nth data of table 1
$(el).html(data[0][n]);
});
});
$(".price-btn_2").click(function() {
// loop through each <td>
$(".price-table tbody td").each(function(n, el){
// data[1] means table2
// data[1][n] means nth data of table 2
$(el).html(data[1][n]);
});
});
jsbin snippet
Additional:
You don't really need to use .empty().append() when .html() does exactly the same thing. (If you're concern about performance, I don't think the difference could be noticeable)
Selecting by only $("td") could be dangerous, imagine you have two tables on your page.
Read more:
.each() method jquery
javascript array

Related

ScrollTo fires too early resulting in not scrolling all the way

I am making an Angular application which shows a table with a single tr. This row contains multiple td's which contain data. the table is built up like this:
<div class="col" id="TableCol">
<table id="Table">
<tbody>
<tr>
<td *ngFor="let item of items;">
<div
(click)="ItemSelected(item)"
draggable="true"
[class.selected]="item.id == selecteditem?.id"
(dragstart)="dragStart($event, item)"
(drop)="dropItem($event, item)"
(dragover)="dragoverItem($event, item)">
{{item.description}}
</div>
</td>
</tr>
</tbody>
</table>
</div>
The table is scrollable when it overflows its X value
#TableCol{ overflow-x: scroll; }
Now i have a function which adds a td at the right side of this tr.
When this function is called an extra td shows up into my table and scrolling works fine.
The thing I want to achieve is that the table automatically scrolls all the way to the right when I add a new td.
I've tried to call this function right AFTER I've added the new item to the items array.
this.items.push(item);
scrollRight() {
document.querySelector('#mapLocationTableCol').scrollLeft = 10000;}
and
scrollRight() {
document.querySelector('#mapLocationTableCol').scrollTo(10000, 0);}
Both these give the same result:
They scroll my row all the way to the right except for the last element.
I think this is due to the scrollRight() being called before the table is redrawn.
Anyone have a solution to make it scroll after the table is drawn?
edit: I've made a stackblitz example:
https://stackblitz.com/edit/angular-d6lm6k
You should monitor the creation of the table cell with ViewChildren and the QueryList.changes event. In the markup, set a template reference variable on the td elements:
<td #cells *ngFor="let item of items;">
In the code, use ViewChildren to get the list of these elements, and subscribe to the QueryList.changes event in ngAfterViewInit. If a new cell was added, do the scrolling. In the code below, I set a flag to make sure that automatic scrolling is performed only when desired.
#ViewChildren("cells") cells: QueryList<ElementRef>;
private shouldScrollRight = false;
...
addItem() {
this.shouldScrollRight = true;
this.items.push(item);
}
ngAfterViewInit() {
this.cells.changes.subscribe((cellList) => {
if (this.shouldScrollRight) {
this.shouldScrollRight = false;
this.scrollRight();
}
});
}
See this stackblitz for a demo.

Fade out Columns in HTML-Table with jQuery: Why is .fadeTo() so slow?

I want to fade out all cells in a column of my HTML-table when I click on a button in the Header of this col. For that I run the following JavaScript:
...
myDOMElement.find(".headerIcon").bind("click", function(event){
var colo = $(event.target).parent().attr("id"); // colNo is stored as Icons id
myDOMElement.find(".myTable").find("tr").find("#"+colo) // each tr has an id according to its colNumber
.each(function(index) {
$(this).fadeTo(0,0.2);
}
});
});
This works as desired but is relative slow even on tables with only 200 rows.
Is there a better (faster) way to do this?
"#"+colo is (must be!) a unique id. No reason for the cascaded finds - and if not, you are facing other problems:
...
myDOMElement.find(".headerIcon").bind("click", function(event){
var colo = $(event.target).parent().attr("id"); // colNo is stored as Icons id
$("#"+colo).fadeTo(0,0.2);
});
});
[edit]
As per the comments, in order to fade out Columns, the id must better hold information about row and column and will thus be unique per cell:
<tr>
<td id="1.1">scheme is <col>.<row></td>
<td id="2.1">
...
<tr>
<td id="1.2">
<td id="2.2">
...
...
myDOMElement.find(".headerIcon").bind("click", function(event){
var roco= $(event.target).parent().attr("id");
var col = roco.split('.')[0];
var row = roco.split('.')[1];
// now search all TD#s which have the clicked col (1.~) as a beginning of their ID
myDOMElement.find("td[id^='" + col + ".']").each(function(index) {
this.fadeTo(0,0.2);
});
});
see also jQuery Attribute selector
Since I dont need the animation provided by .fadeOut() I fond a faster way to do this:
myDOMElement.find(".myTable").find("tr").find("#"+colo).css({opacity:0.2});

Trying to remove a child html element with javascript

I have 3 tables in my boostrap tab. Each tab as a table. The rows of this table is dynamically generated with csharp asp.net code. Right I Want a scenario were if a user click on the row of the first table, the clicked role of the first table get remove from the first table and is added to the rows of the second table.
My challenge as been getting to remove the row after the onClick process.
<tbody>
<tr id="kayode#yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515"
data-parentid="kayode#yahoo.com"
href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com"
operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Active</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>02:52:55</td>
<td>271.0.0.1</td>
</tr>
</tbody>
My javascript code which I am trying to use to remove the row after the Click event.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
//alert(parentid);
//we are going to remove the role from this field
var element = document.getElementById(parentid);
element.parentNode.removeChild(element); //This line is a problem says
//document.querySelector("tablebody4 first").appendChild(element);
console.log(element);
}
This is untested, but I imagine jQuery will greatly reduce your headache here:
function updateWaitingState(sender) {
var parentId = $(sender).attr("data-parentid");
$('#' + parentId).appendTo('.tablebody4:first');
}
You may need to adjust the selector in the appendTo function, as it was a guess on my part.
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
var element = document.getElementById(parentid);
$(element).appendTo('.tablebody2:first');
}

jQuery parent() in table

I want to access the div tag in the following HTML code:
<table>
<div class="rowBound">
<tr onclick="expandLastResultDetails(this);">
<td class="c1">56835-14513</td>
...
</tr>
<tr class="rowDetails">
<td colspan="0">
<div style="background-color: #0F9;"> expandable
</div></td>
</tr>
</div>
</table>
But jQuery commands just give me a TBODY instead of my DIV ..
This is what I was doing in another case:
function expandNavContent(navEntryTitle) {
var content = $(navEntryTitle).parent().children('.navContent');
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
What I want:
rowDetails should be animated with slideToggle if someone clicks on the tr
If I use this code:
function expandLastResultDetails(tableEntry) {
var content =$(tableEntry).parent().children('.rowDetails');
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
It toggles ALL rows but it should just toggle ONE row so I nested them into a division, maybe that was wrong
Try this:
$('tr.rowDetails').find('div');
But, your Markup is not valid. tr is element of table, not for div.
To get the outer parent div:
$('tr.rowDetails').closest('div');
After edit
function expandLastResultDetails(tableEntry) {
var content =$(tableEntry).next('.rowDetails'); // will point to next tr
$(content).slideToggle('slow', function () {
// Animation complete.
});
}
Try $('.rowDetails').closest('div.rowBound');
It will bubble from the current element (outwards) until it find a div element.
Hope it helps
What command did you try? You could have used this:
$(".rowDetails tr td div");
And moreover, there cannot be a <tr> inside a <div>!
Since your markup is invalid the browser will propably insert the tbody and table for you (look at the markup in FireBug/Dev tools). Something like $(".rowDetails").parent().parent().parent() could work (in some browsers) but I'd recommend fixing the markup instead

Querying a table in Jquery

I have encountered this code
$("#search").keyup(function(){
var val = $.trim(this.value).toLowerCase();
$("table > tbody > tr:gt(0) ").hide();
if(val.length){
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
} else $("table > tbody > tr:gt(0)").show();
});
For Querying a a table in jQuery. here's the HTML markup
<p>
<input id = "search" type = "text">
</p>
<table id ="accounts">
<tr>
<th>Username</th>
<th>Password</th>
</tr>
<tr>
<td>Metasm</td>
<td>password1992</td>
</tr>
<tr>
<td>superadmin</td>
<td>adminpassword</td>
</tr>
<tr>
td>skyrocketeer</td>
<td>thejetsons</td>
</tr>
</table>
Basically it works. but the I am very confused with regards to the jQuery code.
My Question: in this part of code
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
What does this part specifically do? and what does it return?
$("table > tbody > tr:gt(0) > td") - This lines of code states that you want all <td> elements within a <table> element that are in a <tbody> element, who's <tr> element's index is greater than 0 (ie - skip the first row. gt() is simple Greater Than). The > selector states that we only want elements in the first level of children - we don't want to drill down further than the first set of child elements.
The .filter() function will reduce the set of matched elements to those that match the selector or pass the function's test.
The conditional statement here is looking for a certain index of a search string val, within the innerHTML of each element.
this.innerHTML.toLowerCase().indexOf(val) >=0
So what this is saying (remembering that we are iterating over all the elements we found from our first selector) is that we are looking for an occurance of the string val within the innerHTML of the element. The innerHTML is also being passed through the toLowerCase() function, who's name suggests is function - converts all characters to their lowercase form.
Phew...Now after all this we are left with a certain list of elements. Elements that met all of our specifications above. For each of these elements, the code will locate their parent (remember we are talking about <td> elements, so their parents should be <tr>) with the .parent() function and display them on screen with the .show() function.
For the first selector - $("table > tbody > tr:gt(0) > td"), I find sometimes its easier to read it backwards (in your mind) to understand the hierarchy...
Return the -
I'm looking for <td> elements,
that are inside <tr> elements (but not the first one),
that are inside a <tbody> element
that all reside within a <table> element.
Now for some sample input and output.
Given the value of val is "jet", the function would display the last <tr> - the one with the string - thejetsons.
Given the value of val is "password", the function would display the two <tr> elements in the middle. The ones that contain "password1992" and "adminpassword".
I hope this sheds some light on your problem!
$("table > tbody > tr:gt(0) > td") will select all td inside tr:gt(0)... this is a basic jquery selector.
With those td selected, apply a filter based on returned value of the function, if return true, the td will be select.
Then your function: return this.innerHTML.toLowerCase().indexOf(val) >=0 means if the td contains a string (val) will return true, otherwise.
All of this equal to
$("table > tbody > tr:gt(0) > td:contains('"+val+"')").parent().show();
This code select all td elements in all tr elements except first one, then we execute the function for each element as context, if for element the function return false, then it is excluded from jquery 'array', then for all filtered elements we get tr elements in which they are and show them. Into the function we get inner text and search it in search query.

Categories