<script type="text/javascript">
function retrieveFieldsOfListView(){
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle('pranav_list');
var view = list.get_views().getByTitle('Main');
this.listFields = view.get_viewFields();
clientContext.load(this.listFields);
clientContext.executeQueryAsync(Function.createDelegate(this,
this.onListFieldsQuerySucceeded9), Function.createDelegate(this,
this.onListFieldsQueryFailed));
}
function onListFieldsQuerySucceeded9() {
var fieldsinfo='';
var fieldEnumerator = listFields.getEnumerator();
while (fieldEnumerator.moveNext()) {
var oField = fieldEnumerator.get_current();
var fType = oField.get_fieldTypeKind();
fieldsinfo +='\n '+oField.get_title();
}
alert(fieldsinfo);
}
</script>
I want to show the fields of the view using javascript.
Note: My list name is "pranav_list" and view is "Main".
Help..!
SP.View.viewFields property returns field names but not a Field client object collection.
The following example demonstrates how to print field names from a View:
function retrieveFieldsOfListView(listTitle,viewName){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var view = list.get_views().getByTitle(viewName);
var viewFields = view.get_viewFields();
context.load(viewFields);
context.executeQueryAsync(printFieldNames,onError);
function printFieldNames() {
var e = viewFields.getEnumerator();
while (e.moveNext()) {
var fieldName = e.get_current();
console.log(fieldName);
}
}
function onError(sender,args)
{
console.log(args.get_message());
}
}
Related
I have a custom list Sections that has values based on a date range. I have a contact list that will be a list of individuals and has a Sections lookup in this custom list. I want the dropdown for the Sections lookup only display those values that are within today's date.
I have code to remove the values (There is probably a better way, I'm walking through them), then I have code that will look up the list and find the appropriate values that are "current".
I don't know how to add these values to the Dropdown. All of my code works, but need the details to add the appropriate values to the dropdown.
<script type="text/javascript">
$(document).ready(function() {
//don't exectute any jsom until sp.js file has loaded.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', GetSections);
});
function GetSections()
{
var dtToday = new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate() );
// Remove all values from Section
$("select[title='Section'] option").each(function(){
$(this).remove();
});
var ctx = new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Sections');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query></Query></View>');
var collListItems = list.getItems(camlQuery)
ctx.load(collListItems);
ctx.executeQueryAsync(
function(){
var swListItms = collListItems.getEnumerator();
while (swListItms.moveNext())
{
var swItm = swListItms.get_current();
var itmSDt = swItm.get_item("BeginDate");
var itmEDt = swItm.get_item("EndDate");
var quest = swItm.get_item("Title");
if((dtToday >= itmSDt) && (dtToday <= itmEDt))
{
console.log("yes-"+quest);
$("select[title='Section'] option").prepend('<option value="" selected="selected">--select--</option>')
} //else {
//console.log("no-"+quest);
//}
}
},
function(sender,args){
console.log("Request Failed."+args.get_message() + "\n" + args.get_stackTrace());
}
);
}
</script>
Thank you in advance.
Modify the code snippet as below:
<script type="text/javascript">
$(document).ready(function() {
//don't exectute any jsom until sp.js file has loaded.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', GetSections);
});
function GetSections()
{
var dtToday = new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate() );
// Remove all values from Section
$("select[title='Section'] option").each(function(){
$(this).remove();
});
var ctx = new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Sections');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query></Query></View>');
var collListItems = list.getItems(camlQuery)
ctx.load(collListItems);
ctx.executeQueryAsync(
function(){
$("select[title='Section']").prepend('<option value="" selected="selected">--select--</option>')
var swListItms = collListItems.getEnumerator();
while (swListItms.moveNext())
{
var swItm = swListItms.get_current();
var itmSDt = swItm.get_item("BeginDate");
var itmEDt = swItm.get_item("EndDate");
var quest = swItm.get_item("Title");
if((dtToday >= itmSDt) && (dtToday <= itmEDt))
{
console.log("yes-"+quest);
$("select[title='Section']").append("<option value='"+quest+"'>"+quest+"</option>")
}
}
},
function(sender,args){
console.log("Request Failed."+args.get_message() + "\n" + args.get_stackTrace());
}
);
}
</script>
<select title="Section"></select>
I have a simple JS form on my SP16 site where I added this standard people picker:
$(document).ready(function() {
initializePeoplePicker('pickerUAT');
function initializePeoplePicker(peoplePickerElementId) {
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = false;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '269px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}
});
I am able to get the selected value (as a display name, email, whatever) from the picker like this:
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.pickerUAT_TopSpan;
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var addThisUser;
if(userInfo != null)
{
addThisUser = userInfo.Key;
}
return addThisUser;
}
And I have a list to which I can add other values taken from other form fields, usually through document.getElementById("XXX").value and this piece of code:
function addSubUser(addThisValue) {
var clientContext = new SP.ClientContext(siteurl);
var itemCreateInfo = new SP.ListItemCreationInformation();
var valueToAdd = addThisValue;
var list = clientContext.get_web()
.get_lists()
.getByTitle("UAT");
this.oListItem = list.addItem(itemCreateInfo);
oListItem.set_item('userUAT', valueToAdd);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
However, this code doesn't work for the value taken from the people picker. Console.log(typeof addThisUser) tells me the value I get from the picker is just a string, do I assume correctly that I cannot simply add a string to a person/group column? In any event, how can I make it work?
I think You may try to update the filed using two different methods
as lookup giving ID of user
var LookupSingle = new SP.FieldLookupValue();
LookupSingle.set_lookupId(2); // UserId
oListItem.set_item('SomeLookupColumn', LookupSingle);
as Single User Field
var singleUser = SP.FieldUserValue.fromUser('name surname');
oListItem.set_item('SomeSingleUserColumn', singleUser);
Sample test script in my local SharePoint 2016(multiple user field).
CustomPeoplePicker:
<div id="peoplePickerDiv"></div>
<input id="Button1" onclick="SaveItem()" type="button" value="button" />
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/sp.js"></script>
<script src="/_layouts/15/1033/strings.js"></script>
<script src="/_layouts/15/clienttemplates.js"></script>
<script src="/_layouts/15/clientforms.js"></script>
<script src="/_layouts/15/clientpeoplepicker.js"></script>
<script src="/_layouts/15/autofill.js"></script>
<script src="_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
})
function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDiv', null, schema);
}
function SaveItem() {
var ctx = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle("MyList");
var listCreationInformation = new SP.ListItemCreationInformation();
var listItem = list.addItem(listCreationInformation);
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
var finalusers = new Array();
for (var i = 0; i < users.length; i++) {
var arryuser = users[i];
finalusers.push(SP.FieldUserValue.fromUser(arryuser.Key));
}
listItem.set_item("Title", "Title");
listItem.set_item("Requestor", finalusers);
listItem.update();
ctx.load(listItem);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
console.log(listItem);
}),
Function.createDelegate(this, function (sender, args) {
alert('Query failed. Error: ' + args.get_message());
})
);
}
</script>
I have a function that creates a chart in a new tab. I have done this in javascript. How should this be converted into AngularJs.
function OpenWin() {
var w = window.open();
w.document.open();
w.document.write('<div id="container" style="width:100%; height:400px;"></div>');
w.document.write('<select id="type" onchange="ChartFunc(this.value)"><option value="line">line</option><option value="column">column</option> <option value="area">area</option><option value="bar">bar</option></select>');
var scriptHead = w.document.createElement("SCRIPT");
var scriptHead1 = w.document.createElement("SCRIPT");
var link = "http://code.highcharts.com/highcharts.js";
var link1 = "http://code.highcharts.com/modules/exporting.js";
scriptHead.onload = function() {
var script = w.document.createElement("SCRIPT");
w.document.body.appendChild(script);
var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); var jsona = JSON.parse(a); var chart = new Highcharts.Chart(jsona);function ChartFunc(value){ console.log(value); jsona.chart.type = value;var chart = new Highcharts.Chart(jsona); }');
script.appendChild(js);
w.document.close();
scriptHead1.src = link1;
w.document.head.appendChild(scriptHead1);
}
scriptHead.src = link;
w.document.head.appendChild(scriptHead);
}
Lets say I have the following code snippet:
function Airplane(id) {
this.id = id;
}
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
Is there any way to get the total number of Airplane objects created something like Airplane.getCreatedLength()?
You could keep track of those in a property attached to the constructor:
function Airplane(id) {
this.id = id;
Airplane.instances += 1;
}
Airplane.instances = 0;
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
console.log(Airplane.instances) // 3
I need to pass a list from my MVC-controller to a javascript in my view.
Here's the method in my controller
private void PopulateChart() {
var diagramItem = new DiagramPoll();
var diagramList = new List<DiagramPoll>();
diagramItem.Color = "#F7464A";
diagramItem.Label = "System 1";
diagramItem.Value = "10";
diagramList.Add(diagramItem);
diagramItem.Color = "##FDB45C";
diagramItem.Label = "System 2";
diagramItem.Value = "20";
diagramList.Add(diagramItem);
ViewBag.MyValues = JsonConvert.SerializeObject(diagramList, Formatting.None);
}
And in the script-section in the view-file:
<script>
$(document).ready(function() {
var chartValues = #Html.Raw(ViewBag.MyValues);
//This is what I would like to do:
foreach (var item in chartValues) {
var color = item.Color;
var label = item.Label;
var value = item.Value
}
});
</script>
I need to extract the variables above to send them as input parameters to a jQuery-chart.
Thank you!
For passing values from view to script you need to add it in quotes. Change your script to as below
<script>
$(document).ready(function() {
var chartValues = '#ViewBag.MyValues';
});
</script>
Also you would not be able to iterate through it, firstly you will need to convert serialized json object to proper json object.
Something like this and then run foreach over json object.
var chartData = $.parseJson(chartValues);
foreach (var item in chartData ) {
var color = item.Color;
var label = item.Label;
var value = item.Value
}
Or
var chartData = JSON.parse(chartValues);
but you will have to convert chartValues for sure
you can try something like this:
#model IList<WebApplication2.Models.DiagramPoll>
<script type="text/javascript">
$(document).ready(function() {
//This is what I would like to do:
#foreach (var item in Model) {
var color = item.Color;
var label = item.Label;
var value = item.Value;
}
});
public ActionResult About()
{
var diagramItem = new DiagramPoll();
var diagramList = new List<DiagramPoll>();
diagramItem.Color = "#F7464A";
diagramItem.Label = "System 1";
diagramItem.Value = "10";
diagramList.Add(diagramItem);
diagramItem.Color = "##FDB45C";
diagramItem.Label = "System 2";
diagramItem.Value = "20";
diagramList.Add(diagramItem);
return View(diagramList);
}