persist node state between postbacks with jquery cookie plugin - javascript

I have the following html table
<table id="{64ED3A94-5833-4CC7-869F-CCE583B498BE}" class="ms-listviewtable"
width="100%" cellspacing="0" cellpadding="1" border="0"
xmlns:o="urn:schemas-microsoft-com:office:office" dir="none">
<tbody id="tbod23-1__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-2__" isloaded="true" style=""></tbody>
<tbody id="tbod23-3__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-4__" isloaded="true" style=""></tbody>
<tbody id="tbod23-5__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-6__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-7__" isloaded="true" style="display: none;"></tbody>
</table>
This table is autogenerated by a sharepoint xsltlistviewwebpart (didnt post in sharepoint as the question is more jquery+html related).
this is a treeview with nodes, when i expand a collapsed node it changes style from
style="display: none;"
to
style=""
The problem: the webpart does not remember which nodes were collapsed, so on each postback it resets all to expanded. What I need to do, is to remember the node state (expanded or collapsed) in a jquery cookie, and to retrieve it on postbacks (so, to persist the node state).
So far I got:
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("RememberClickedState");
function RememberClickedState()
{
var dv = $('.ms-listviewtable');
var items = [];
items = dv.find('tbody[id^="tbod"]');
$.cookie("itemListState", items);
alert(items[0]);
alert(items[1]);
}
</script>
Can anyone please provide some pointers on how to do this. Im a bit dazed and confused about the events themselves, on page_load I should save the cookie but also retrieve it somehow.
Also "items" array stored all 7 elements which is good, but when i try alert(items[0]); I get undefined.
Thank you

I suggest you to create string of this and then parse this string back... kind of like that:
var items = '';
function RememberClickedState() {
$('.ms-listviewtable tbody').each(function(){
tid = $(this).attr('id');
tvisible = $(this).is(':visible');
items += tid+':'+tvisible+','
})
//$.cookie("itemListState", items);
$('body').append(items+'<br/>');
}
function RestoreClickedState() {
//string = $.cookie("itemListState")
var string = items; //temporary
var cookies = string.split(',');
$.each(cookies, function(i, val){
val = val.split(':');
show = (val[1] == 'true' ? true:false);
item = $('.ms-listviewtable').find('#'+val[0]);
show ? item.show() : item.hide();
$('body').append('#'+val[0]+' is '+ 'display:'+show+'<br/>');
})
}
$(document).ready(function(){
RememberClickedState();
RestoreClickedState();
})
Here is DEMO:
http://jsfiddle.net/MYexv/3/

Related

Iterate through selected rows in Datatables

I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.

JSON Object into Mustache.js Table

I'm trying to create a table with a JSON Object using Mustache.js.
I wanted it to show two rows, however it's only showing the second row only.
I suspect that the first row is being overwritten by the second when it's being bound again in the loop.
How do I work my way around it? Or is there a better structure I should follow?
Javascript:
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
Template :
<script id="user-template" type="text/template">
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</script>
table:
<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable">
</tr>
</table>
In additon to your own solution, you should consider using mustache to repeat the row for you:
<script id="user-template" type="text/template">
{{#people}}
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = {people: JSON.parse(text)};
$(document).ready(function() {
var template = $('#user-template').html();
var info = Mustache.render(template, obj);
$('#ModuleUserTable').html(info);
});
I figured out that instead of
$('#ModuleUserTable').html(info);
it should be :
$('#ModuleUserTable').append(info);
Template should be :
<script id="user-template" type="text/template">
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
</script>
and ID should not be on the table row tag. Instead it should be on the table itself:
<table border="1" id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
The moment when it appends, it adds a new row into the table with the JSON data.

Jquery script not running in PHP

I'm new to the jquery scripts, but I have an HTML table structured as follows inside my php code:
print <<<End_Of_HTML
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<thead>
<tr>
<th align="left" class="job_code">In/Out</th>
<th align="center">Time</th>
<th align="center">Date</th>
<th align="center" class="hrs" title="Regular work hours.">Hrs</th>$overtime_col$total_col
<th align="left" class="notes">Notes</th>
</tr>
</thead>
<tbody>
End_Of_HTML;
I then have a PHP-MySQL query populate that table with results and wanted to total up the hrs class based on the job_code classes value. I have this jquery script, which works on JSFiddle (http://jsfiddle.net/Lj6he/)
$(document).ready(function(){
var temp = [];
$('.job_code').each(function(index, element){
var text = $(this).text();
temp.push(text);
});
// remove duplicates
var job_code = [];
$.each(temp, function(index, element){
if($.inArray(element, job_code) === -1) job_code.push(element);
});
var sum = {};
$.each(job_code, function(index, element){
var total = 0;
$('.job_code:contains('+element+')').each(function(key, value){
total += parseInt($(this).next('td.hrs').text());
sum[index] = {'job_code' : element, 'total': total};
});
});
console.log(sum);
$.each(sum, function(index, element){
$('#total').append('<p>Total for '+element.job_code+': '+element.total+'</p>');
});
});
But when I enter it into my PHP file as follows it doesn't display what is seen on JSFiddle....any ideas are greatly appreciated. Thanks.
$PAGE_SCRIPT = <<<End_Of_HTML
<script type="text/javascript" src="scripts/jquery.totals.js"></script>
End_Of_HTML;
It just seems to not be displaying the results of the jquery on the page. Any ideas would be great.
Drop this line into the head section of your html output.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
that will import jQuery for you
ps, be sure to include it before any dependencies
You are appending your output to a non-existent element with id #total
Ensure the jquery library is referenced prior to your javascript code import.
The sample PHP code is missing
<div id="total">
</div>
This is the Div where the content is added.

knockout observable array is not updating view on removing elements from array

Here is my view model code
var TopicsViewModel = function() {
var self = this;
var fakeTopicData =
[
];
self.createProfile = function () {
alert("came to create profile");
};
self.editProfile = function () {
alert("came to edit profile");
};
self.removeProfile = function (profile) {
alert("came to remove profile");
fakeTopicData.pop();
self.topicsArr(fakeTopicData);
};
var refresh = function() {
self.topicsArr = fakeTopicData;
};
self.topicsArr = ko.observableArray([]);
refresh();
};
ko.applyBindings(new TopicsViewModel());
Here is my html for the view:
<hr />
<hr />
<table class="table table-striped table-bordered table-condensed">
<tr >
<th>Area</th>
<th>Name</th>
<th>Link</th>
<th>Description</th>
<th>Why</th>
</tr>
<tbody data-bind="foreach : topicsArr">
<tr>
<td data-bind="text :area"> </td>
<td class=""><a data-bind="text:name, click:$parent.editProfile"></a></td>
<td data-bind="text:link"> </td>
<td data-bind="text:desc"> </td>
<td data-bind="text:why" ></td>
<td><button class="btn btn-mini btn-danger" data-bind="click:$parent.removeProfile">remove</button></td>
</tr>
</tbody>
</table>
<script src="~/Scripts/Topic.js"></script>
The view initially display all the Topics in my fakeData Array.
On clicking the remove Button, I am trying to remove an element from the array, and expected the view to refresh and not show the removed item any more. However the view still shows all the 3 topics.
Could someone please point to what I might be doing wrong.
I spend a long time researching the other similar queries on stackoverflow, but am still stuck. Thanks so much for any insight into this issue.
You are replacing your observable array called topicsarr with one which isn't observable in your refresh method...
Change
var refresh = function() {
self.topicsArr = fakeTopicData;
};
to
var refresh = function() {
self.topicsArr(fakeTopicData);
};
you have 2 issues in your code.
First, you are setting your observableArray topicsArr with non observableArray or normal array in refresh function. Instead use self.topicsArr(fakeTopicData)
Second, in function removeProfile you are using pop() to remove profile element. From KnockoutJS documentation:
myObservableArray.pop() removes the last value from the array and
returns it
So, it's better to use remove(item) and pass to it your profile element or loop through your array and remove that specific item
myObservableArray.remove(someItem) removes all values that equal
someItem and returns them as an array

How to select a row from dynamic table on mouseclick event

How can get a row's value on mouse click or checking the checkbox preferably from the below given html table?
Here is the js for getting values for my table from a xml using spry
var ds1 = new Spry.Data.XMLDataSet("xml/data.xml", "rows/row");
var pv1 = new Spry.Data.PagedView( ds1 ,{ pageSize: 10 , forceFullPages:true, useZeroBasedIndexes:true});
var pvInfo = pv1.getPagingInfo();
Here is the Div with spry region containing the table that gets populated from pv1 (see js part)
<div id="configDiv" name="config" style="width:100%;" spry:region="pv1">
<div spry:state="loading">Loading - Please stand by...</div>
<div spry:state="error">Oh crap, something went wrong!</div>
<div spry:state="ready">
<table id="tableDg" onclick="runEffect('Highlight', 'trEven', {duration: 1000, from: '#000000', to: '#805600', restoreColor: '#805600', toggle:true}, 'Flashes a color as the background of an HTML element.')"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="email"><b>Email</b></th>
</tr>
</thead>
<tbody spry:repeat="pv1">
<tr class="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
<tr class="trEven" name="trEven" id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying the below code but still I am not getting the alert and hence none of the answers are also not working. I know the syntax n all are everything correct, but i am not able to figure out what is the problem here!
//inside $(document).ready(function()
$("#chkbHead").click(function() {
alert("Hi");
});
My page has other tables too for aligning some contents. So when I use the below code it works perfectly on those tables except the one in the question. It might be the problem because there are only 2 tr in the table which gets populated by a spry dataset and hence not getting identified properly. May be, I am not sure, just trying to help improve my understanding
$('tr').click(function() {
alert("by");
});
The values of a Row you will get with:
$('#tableDg tbody tr').live( 'click', function (event) {
$(this).find('td').each( function( index, item ) {
if ( $(this).has(':checkbox') ) {
alert( $(this).find(':checkbox').val() );
} else {
alert( $(this).text() );
}
};
});
What exactly do you mean by value of a table row? You can get the inner html of a table row like this:
var html = '';
$('tr').click(function() {
html = $(this).html();
});
You can get attributes of the table row (e.g. it's Id) like so:
var id = '';
$('tr').click(function() {
id = $(this).attr('id');
});
Alternatively you can get the value of nested elements such as a text input like so:
var text = '';
$('tr').click(function() {
text = $(this).find('#myTextBox').val();
});
EDIT
This is how to change the checked attribute of a checkbox nested in a table row:
$('tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
EDIT
As the table rows are being loaded dynamically - the $().click() event binding method will not work, because when you are calling it - the table rows do not exist, so the click event cannot be bound to them. Instead of using $().click use the jQuery live method:
$('tr').live('click', function() {
// do stuff
});
This binds the click event to all current table rows and all table rows that may be added in the future. See the jQuery docs here
you have to use Spry Observer,
something like this:
function funcObserver(notificationState, notifier, data) {
var rgn = Spry.Data.getRegion('configDiv');
st = rgn.getState();
if (notificationState == "onPostUpdate" && st == 'ready') {
// HERE YOU CAN USE YOUR JQUERY CODE
$('#tableDg tbody tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
}
}
Spry.Data.Region.addObserver("configDiv", funcObserver);

Categories

Resources