jQuery Datatable get the page number of element - javascript

We have used jQuery Datatables plugin to save update records in multiple rows.
Also validation is built for all the columns, once validation is failed.
We have the following line of code to focus on element for which validation is failed.
$(this).focus();
However this will not work if validation fails on some other page( $(this) is not on current).
As a workaround to this we thought we will click on the page number hyperlink
$(#identifier).trigger('click');
The problem is
"How to know if an element with id A ( $(#A)) is in which page of jQuery Table ?"
Once we know that problem will be solved.

Here, I've written a js function to move you to the page with a given row (row with class "selectedItem" in this case). It should be possible to rewrite the code to find any elements, not just rows, in case you need to.
function moveToPageWithSelectedItem() {
var numberOfRows = itemsTable.data().length;
var rowsOnOnePage = itemsTable.page.len();
if (rowsOnOnePage < numberOfRows) {
var selectedNode = itemsTable.row(".selectedItem").node();
var nodePosition = itemsTable.rows({order: 'current'}).nodes().indexOf(selectedNode);
var pageNumber = Math.floor(nodePosition / rowsOnOnePage);
itemsTable.page(pageNumber).draw(false); //move to page with the element
}
}

Related

Dynamically insert id into table element

I’m working on what I thought would be a simple project but is something I’m struggling with. I’m wondering if someone could review what I’m trying to do and give me some pointers on how to proceed.
The concept here is fairly simple...I thought - identify each table in an html file based on the "table" element, count the number of rows in each table and if the table has more than 10 rows, dynamically create a unique id for the table.
I know how to do all this (for the most part) but it doesn’t respond how I anticipate.
Here’s my initial javascript code attempt to dynamically create and insert the unique table id’s:
/* This function dynamically sets a unique id to each table found in the html page: */
function set_table_id(){
var num_tables = document.getElementsByTagName("table"); //determine the number of “table” nodes in the html
//alert("set_table_id function: The total number of table elements are: " + num_tables.length);
if (num_tables) { //if one or more table nodes are found…
var id_name = "dataTbl_"; // create the prepend string for table id value
var n = 1;
var i;
//for each table node found…
for (i=0; i < num_tables.length; i++) {
var id_name_new = id_name + n; //create the next unique table id from the prepend string
n++;
num_tables[i].id = id_name_new; //apply the latest table id to the current table
//this will be the call to the function to apply the datatables javascript to each table that has more than 10 rows:
//num_tables[i].dataTable();
}
}
}
When I run the above js code there are no errors when I review the Inspect Element Console, but the unique id’s never get inserted into the table elements.
This should run through the html code, identify each table and dynamically apply (insert) a unique id to each table but it's not.
Any help is greatly appreciated.
This jQuery selector will find all tables that have 10 or more <tr> children and apply the ID and DataTables to each.
$(document).ready(function() {
$("table > tbody > tr:nth-child(10)").closest("table").each(function(index) {
var tableId = "dataTbl_" + (index + 1); //index is zero-based, so add 1
$(this).attr("id", tableId); //set the ID attribute
$(this).dataTable();
}
);
});
Heres is a JSFiddle, based on the on in your comment, which demonstrates it:
https://jsfiddle.net/5cgbdLzt/2/
Within that fiddle, I added a button that will alert the IDs to you, where you can see clearly that the ID of the table with fewer than 10 rows has an ID that is undefined.
Note: DataTables uses jQuery as a dependency, so it's assumed you can use jQuery selectors rather than strictly vanilla JS.

Targeting specific row/line of textarea and appending that row

I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.

Can someone help me apply the js 'this' keyword to an iterated jq select expression

Here's my latest version of this code. The 1st line iterates through the rows of a table skipping over the 1st row. For each row I test to see if the (class='dim') state of one of 8 tag elements (index j) on that row matches the corresponding !'dim' state of a set of 8 filters that the user can toggle. The idea is to set any rows where the 'active' filter / 'dim' tag states line up, to the 'hide' class, so they can disappear from the table that the user sees. The CSS for disappearing it is: .hide {display:none;}
It's that last 'if' statement that's killing me. I've tried dozens of versions but I always get some form of syntax error, undefined variable, etc. In that line of code here I've removed my latest set of +, ', " characters to better show clearly what I'm trying to do.
I don't just want something that works to replace this code. And I'm not interested in the shortest trickiest way to do it. I'd like to see some simple obvious code that I could easily understand a year from now so I can solve problems like this myself. Thanks in advance.
var thisRow = $('tbody tr:gt(0)').each(function() {
for (var i=0,j=4;i<8;i++,j++) {
if (!$('.butt').eq(i).hasClass('dim')) {
if (thisRow.nth-child(j)).hasClass('dim')) $(this).addClass('hide');
else $(this).removeClass('hide');
}
}
}
Above this line is the question as I first asked it. Below this is the complete function in case anyone else might find this useful. Thanks to Mr. Pavlikov for the lesson!
function filterTbl() { //Hide rows that don't satisfy all active filters
var butts=$('.butt'); //Each filter button has class 'butt'
$('tbody tr:gt(0)').each(function() { //iterate each table row except the 1st
var thisRow = $(this); //the row being examined
var chilluns = thisRow.children(); //all td's in the row being examined
for (var i=0,j=4;i<8;i++,j++) {
if (!butts.eq(i).hasClass('dim')) { //If this filter is active
//and If the corresponding tag is not active (is 'dimmed'), then hide this row
if (chilluns.eq(j).hasClass('dim')) thisRow.addClass('hide');
else thisRow.removeClass('hide'); //else unhide this row
}
}
});
}
First of all you should be getting thisRow variable like this (not like you are currently doing)
$('tbody tr:gt(0)').each(function() {
var thisRow = $(this);
}
And what does nth-child stand for? Use nth-child selector correctly or use siblings at least if you are willing to compare one row with other rows. I didn't quite understand what are you trying to do, but hope this helps.
And some usefull tips. You do not need to find $('.butt') EVERY TIME in the loop, just find it once before your each loop:
var butts = $('.butt');
So now you will be able to replace
$('.butt').eq(i)
with
butts.eq(i)
This is significant speedup.
Also if n-th child you are trying to find is something that is inside thisRow, find children and do .eq() on them.

JavaScript code won't work On My Blogger Site

I have made JavaScript code using the fiddle.com website. But in fiddle I can only make it work by using the
no wrap (body)
option. I'm not sure what this option does. The link for the Fiddle is here. I added this script to my Blogger blog, but it would not work.
Code
function getTotal(){
var form = document.theForm;
var inputs = form.getElementsByTagName('input');
var length = inputs.length;
var total = '0';
for (i = 0; i<length-1; i++){
if(inputs[i].type == 'radio'){
var checked = inputs[i].checked?1:0;
if(checked){
var value = inputs[i].value.split("~~")[0];
total -= -value;
}
}
}
document.getElementById('totalspan').innerHTML="Toplam Fiyat: "+ total + " tl"
total='0';
}
The script is to calculate a total price of the selections. You can see it in the fiddle. Also, I have it on Blogger, but as I said it's not working.
The link to my blog is here.
no wrap (body) means that your script will be inserted in new script tag inside body tag, no wrap (head) means that your script will be inserted in new script tag inside head. You can read about it on jsFiddle help
Other options will wrap your JS code inside particular DOM event handlers (onLoad and onDomReady)
Script errors on your site tells me that calculateTotal is not defined, so please check your naming.
Why do you use string when calculating total? You can safely use native JS parseInt funciton.
Another point that using form click event is wrong, you should use change event of your inputs.
Simplest option for you is to use jQuery like this:
$('[name="CPU"], [name="OperatingSystem"], [name="Case"]').on('change', updateTotal);
function updateTotal {
var total = 0;
// calculate your total here
$('#totalspan').text(total);
}
Please check my 5-min fiddle: http://jsfiddle.net/GDXuS/5/
You could also use data- attributes to store price or any other data (see on jQuery site).
And I'm advice you to study some programming languages.

jQuery break out of table

I have a standard HTML formatted table, that dynamically generates the content, via Zend Framework. From which I have an issue altering the form internally PHP side. So I need to alter the tables appearance somehow. With that on the occasion I have an element show up in one of the rows and when this element shows up I want to break out of the table and then do something after it then start the table again.
Basically I want to inject the equivlant of
</tbody></table>/*other stuff*/<table><tbody> after the row containing the one element I seek which in this case is a label.
I tried $("label[for='theLable']").parents('tr').after('</tbody></table><br><table><tbody>') which appears to ignore the ending table parts add the br, and then does a complete open/close tag for table and tbody within the same table I am trying to break out of so inbetween tr tags basically it adds this new table
Whats the best way to approach this concept?
update with jsfiddle link
http://jsfiddle.net/cPWDh/
You can't really modify the HTML of the document the way you're thinking, since it's not a legitimate way to alter the DOM.
Instead, I would create a new table and .append the rows you want to move to it, which will automatically move them from their current location (instead of copying them):
$(document).ready(function() {
var $trow = $('label[for="specialLabel"]').closest('tr'),
$table = $trow.closest('table');
$('<table>').append( $trow.nextAll().andSelf() ).insertAfter($table);
});​
http://jsfiddle.net/cPWDh/1/
this approach won't work in js. What you could do if the table has not too many rows is this:
var nextTable = $("table").after("/*other stuff*/<table id="nextTable"></table>");
//now you loop over the lines of your original table that you want to have after the "break", and move them to the nextTable:
var before = true;
$("table tr").each(function(){
if ($(this).has("[for='theLable']")) {
before = false;
}
if (!before) {
nextTable.append($(this));
}
});

Categories

Resources