Javascript to Read/Count Sharepoint 2010 List Items - javascript

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>

What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

Related

AngularJS Array Not Loading On View Load, but Alerts/Console Work

I am trying to push values into an array as follows, but it is showing as an empty array. Alerting works. I am sure I am missing something obvious. Any clues? I have included the code with the just the array push attempt and another entry of code that has working alerts.
$scope.termsArray = [];
execOperation();
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
}
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the code with working alerts:
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
var termList = "Terms: \n";
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
termList += currentTerm.get_id() + currentTerm.get_name() + "\n";
}
alert(termList);
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the HTML output:
<div> {{termsArray}}</div>
It returns []
Update: If I click in an input box and back out, or click an alert and hit ok, it then loads the array instead of loading on page load.
I was able to track the issue down. It appears that Angular doesn't respect non-Angular functions on load, so I needed to wrap the $scoped array in a $scope.apply. Please see here for details: Execute SharePoint Function On Page Load in AngularJS Application ($scope issue???)

Google Script Active Cell Value and MsgBox

I am trying to get the following code to work. I want a msgbox to appear that has the value of the cell that is being edited. This should be very simple, but I cannot get it to work. Here is the code:
function onEdit(event) {
var s = event.source.getActiveSheet();
var lastColumnRow = s.getLastColumn();
var r = event.source.getActiveRange();
var editRange = s.getActiveRange();
var editCol = editRange.getColumn();
var editRow = editRange.getRow();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}
Thanks in advance!
The problem is just that you missed a pair of parenthesis after getActiveCell.
To help you find problems in functions that you cannot run directly (since you wouldn't get the event object). You can either wrap it in a try-catch, like this:
function onEdit(event) {
try {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
} catch(err) {
Browser.msgBox(err);
}
}
Or create the event object manually, and call a "test" function instead.
function testOnEdit() {
onEdit({source:SpreadsheetApp.getActive()});
}
function onEdit(event) {
var s = event.source.getActiveSheet();
var data = s.getActiveCell.getValue();
Browser.msgBox(data)
}

how can i access a variable in one javascript in another javascript?

Hi guys This is my code of two javascript.i want to access variable defined in first javascript into another script.
1)
<script>
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
</script>
2)
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
</script>
Now my problem is i want to access the editor defined in first javascript as
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
in second javascript.
anyone has answer of this then please help me to do so
If you leave out var while defining variables they will be globally accessible.
So
pre = this;
instead of
var pre = this;
would make pre accessible from every function.
the only way I can think is to pass the variable into the other functions as a variable
function otherJavaFile.myFunction (myVariable);
or alter a variable in the HTML i.e. the custom data-value and then the other script can access it. I don't like global variables.
// Sheet 1
$("#myDiv").attr("data-variable",yourValue);
// Sheet 2
var secondVariable = $("#myDiv").attr("data-variable");
buddy i am not comfortable with jquery...
I hope you are looking forward for the iframes/frames on same document[window sharing].
Based on my knowledge of Javascript DOM to access a variable defined in one document inside another document.You have to use document.importNode(original Node as in other document,boolean) method as per DOM 2.
Do something like this for javacript code ...
documentI(original variable/node present here)- iframe.contentDocument.getElementsByTagName(/Tag name of Node/)...
documentII(node to be cloned here)-
document.importNode(originalNode,True)
I hope this works

Javascript: creating dynamic variables and object names. / html5 localstorage

I'm working on a form that is saved by HTML5 local storage.
When pressing save:
function saveAll(){
var field1 = document.getElementById('field1').value;
localStorage.setItem('con_field1',field1);
var field2 = document.getElementById('field2').value;
localStorage.setItem('con_field2',field2);
var field3 = document.getElementById('field3').value;
localStorage.setItem('con_field3',field3);
var field4 = document.getElementById('field4').value;
localStorage.setItem('con_field4',field4);
var field5 = document.getElementById('field5').value;
localStorage.setItem('con_field5',field5);
var field6 = document.getElementById('field6').value;
localStorage.setItem('con_field6',field6);
}
And when loading the page (fills out the forms):
function ShowAll() {
var field1 = localStorage.getItem('con_field1');
document.conditioning.field1.value = field1;
var field2 = localStorage.getItem('con_field2');
document.conditioning.field2.value = field2;
var field3 = localStorage.getItem('con_field3');
document.conditioning.field3.value = field3;
var field4 = localStorage.getItem('con_field4');
document.conditioning.field4.value = field4;
var field5 = localStorage.getItem('con_field5');
document.conditioning.field5.value = field5;
var field6 = localStorage.getItem('con_field6');
document.conditioning.field6.value = field6;
}
This all works fine, but I want to re-write this in a more fancy and efficient way. I was thinking of something like this:
function ShowAll() {
var field = [];
for (i=0; i<6; i++) {
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
}
But the browser is not enjoying this. Basically I need to create a loop that automatically changes the "field" name in to 'field1, field2, field3' etc. The window thing is working, but I'm just using it wrong.
Anyone has an idea?
Thanks a lot!
function showAll(t1,c1,d1) {
var field1 = localStorage.getItem('con_field1');
console.log(field1)
var field2 = localStorage.getItem('con_field2');
var field3 = localStorage.getItem('con_field3');
}
You should add all of your data to one object, stringify it, then add that to local storage under a single key.
When you load it, grab the one local storage item, parse it, then access the properties on the object.
e.g.
var save = function () {
var data = {
foo: 'bar'
};
localStorage.setItem('myData', JSON.stringify(data));
};
var load = function () {
var data = JSON.parse(localStorage.getItem('myData'));
var someProp = data.foo; // gives you 'bar'
};
It looks like your main problem is that the fields are indexed beginning with 1, but your loop indexes from 0.
What about this?
var field = [];
for (i = 1; i <= 6; i++)
{
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
Also, I'm not 100% on this, but I think using document.getElementByID is more cross-browser compatible than using bracket notation on the window object, but it's been a while since I wrote plain vanilla JS, so don't quote me.
I would try document.purpose["field" + i].value = window['con_field' + i].

Generating JSON Object

I'm trying to parse the rows in a table that I generate using Javascript by adding items to a cart and then create a json object when the user hits save order of all the items and pass it to a php script using $.post in jQuery.
The only trouble I'm having is understanding JSON objects and how to push more items onto the object. I get an error in firebug telling me that devices[i] is undefined. Not really sure how else to accomplish this. I thought it was really just an array.
function Save()
{
var devices = new Object();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
You currently have devices declared as an object, but you're treating it like an array.
You need to declare it as an array of objects.
function Save()
{
var devices = new Array();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i] = new Object();
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
or something like that.
(Updated to show it in your code)

Categories

Resources