Stop Gridview double open when button click?
$("#EDtblraisedocdata tr").remove();
BindEDDocFiles(listTitle,success,error);
$("#EDtblraisedocdata tr").remove();
BindEDDocFiles(listTitle,success,error);
Save items to list By Rest API?
Include Person or group column saving
function SaveItemstoListbyRestApi()
{
var questionValue = $("#txtQuestion").val();
var columnValue = $("#txtQuesDescription").val();
var selectedText = $("#industryMulPost").find("option:selected").text();
var selectedText1 = $("#serviceMulPost").find("option:selected").text();
var askerid = _spPageContextInfo.userId;
alert(askerid);
var data={
"__metadata":
{
"type":"SP.Data.EConnect_x0020_QuestionsListItem"
},
"Industry": selectedText,
"Description": columnValue,
"Services":selectedText1,
"Question":questionValue,
"AskerId": askerid
};
debugger;
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/GetByTitle('EConnect Questions')/items",
type: "POST",
async:false,
data: JSON.stringify(data),
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "POST"
},
success: function(data){
console.log(data);
alert("success");
},
error: function(error) {
console.log(error.responseText);
}
});
}
Upload file to document lirbrary, get files , bind files , Delete Files, Download files, Get last item ID.
//Upload document functionality in RFQ
function RFQreadFile()
{
//Get File Input Control and read th file name
var element = document.getElementById("RFQgetFile");
var file = element.files[0];
var parts = element.value.split("\\");
var fileName = parts[parts.length - 1];
//Read File contents using file reader
var reader = new FileReader();
reader.onload = function (e) {
RFQuploadFile(e.target.result, fileName);
}
reader.onerror = function (e) {
alert(e.target.error);
}
reader.readAsArrayBuffer(file);
}
//var attachmentFiles;
function RFQuploadFile(arrayBuffer, fileName)
{
var clientContext = new SP.ClientContext();
var oWeb = clientContext.get_web();
var oList = oWeb.get_lists().getByTitle('PRDocuments');
//Convert the file contents into base64 data
var bytes = new Uint8Array(arrayBuffer);
var i, length, out = '';
for (i = 0, length = bytes.length; i < length; i += 1) {
out += String.fromCharCode(bytes[i]);
}
var base64 = btoa(out);
//Create FileCreationInformation object using the read file data
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(base64);
createInfo.set_url(fileName);
//Add the file to the library
var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
//Load client context and execcute the batch
clientContext.load(uploadedDocument);
clientContext.executeQueryAsync(RFQQuerySuccess, RFQQueryFailure);
}
function RFQQuerySuccess()
{
$('#RFQgetFile').val("");
getLastItemIdRFQ();
}
function RFQQueryFailure(sender, args)
{
alert('Same name file already exists in this PR, Please rename and Upload');
//console.log('Error in RFQ uploadFile' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
//alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());
}
//function BindEditPRDocFiles(PRNumberIs)
listTitle = 'PRDocuments';
function BindRFQDocFiles(listTitle,success,error)
{
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function()
{
var ClientContext= SP.ClientContext.get_current();
var list = ClientContext.get_web().get_lists().getByTitle(listTitle);
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ClientContext.load(items);
ClientContext.executeQueryAsync(
function() {
RFQsuccess(items);
},
error
);
});
}
function RFQsuccess(items)
{
var e = items.getEnumerator();
while (e.moveNext())
{
var listItemInfo = '';
var item = e.get_current();
DSC1Stageis = item.get_item('Stage');
CuurentPRNumberis = item.get_item('PRNumber');
if(CuurentPRNumberis == prnumberis)
{
if(DSC1Stageis == "RFQ")
{
ItemdocIdis = item.get_item('ID');
$("#RFQtblraisedocdata").append("<tr id='class21' align='middle'>" +
"<td id='class21' align='left' style='font-weight: bold;color: blue;'>"+item.get_item('FileLeafRef')+"</td>" +
"<td id='class21' align='left'><input type='button' id= 'hh' class='class22' value='Delete' onclick='DeleteDocumentFileRFQ("+ItemdocIdis+")'/></td>" +
"<td id='class21' align='left'><input type='button' id= 'hh2' value='Download' onclick='DownloadDocumentFileRFQ("+ItemdocIdis+")'/></td>" +
"</tr>");
}
}
else
{
console.log('Not');
}
}
}
function error(items)
{
console.log('Error in TA error' + args.get_message());
}
//get lastitemid
function getLastItemIdRFQ()
{
var userId = _spPageContextInfo.userId;
var caml = "<View><Query><Where>"
+ "<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'>"
+ userId + "</Value></Eq></Where>"
+ "<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>"
+ "</Query><RowLimit>1</RowLimit></View>";
var ctx = SP.ClientContext.get_current()
var web = ctx.get_web()
var list = web.get_lists().getByTitle("PRDocuments")
var query = new SP.CamlQuery();
query.set_viewXml(caml);
var items = list.getItems(query);
ctx.load(items)
ctx.executeQueryAsync(function()
{
// success actions
var count = items.get_count();
//should only be 1
if (count > 1)
{
throw "Something is wrong. Should only be one latest list item / doc";
}
var enumerator = items.getEnumerator();
enumerator.moveNext();
var item = enumerator.get_current();
DOCidIs = item.get_id();
DocRFQItemUpdate(DOCidIs,prnumberis);
}, function()
{
//failure handling comes here
alert("failed");
});
}
function DocRFQItemUpdate(DOCidIs,prnumberis)
{
DocStage = 'RFQ';
var ctx = new SP.ClientContext.get_current();
var customList = ctx.get_web().get_lists().getByTitle('PRDocuments');
var listItem = customList.getItemById(DOCidIs);
/*Set the value and update*/
listItem.set_item('PRNumber', prnumberis);
listItem.set_item('Stage', DocStage);
listItem.update();
ctx.executeQueryAsync(function()
{
alert("File Uploaded Successfully.");
$("#RFQtblraisedocdata tr").remove();
BindRFQDocFiles(listTitle,success,error);
},function(sender, args)
{
alert('Request failed in RFQ("DocRFQItemUpdate") '+args.get_message() + '\n' + args.get_stackTrace());
$("#RFQtblraisedocdata tr").remove();
BindRFQDocFiles(listTitle,success,error);
});
}
//DeleteDocumentFileRFQ
function DeleteDocumentFileRFQ(ItemdocIdis)
{
$.ajax(
{
url: _spPageContextInfo.webServerRelativeUrl + "/_api/site/rootweb/lists/getByTitle('PRDocuments')/items('" +ItemdocIdis+ "')",
type: "DELETE",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("File has been deleted");
$("#RFQtblraisedocdata tr").remove();
BindRFQDocFiles(listTitle,success,error);
},
error: function (err) {
alert(JSON.stringify(err));
}
}
);
}
function DownloadDocumentFileRFQ(ItemdocIdis)
{
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('PRDocuments')/items?$select=EncodedAbsUrl&$filter=Id eq ('" +ItemdocIdis+ "')";
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: requestUri,
type: 'GET',
dataType: 'json',
headers: requestHeaders,
success: function (data)
{
$.each(data.d.results, function(i,result) {
var path = result.EncodedAbsUrl;
console.log(path);
if (data.d.results[i].FileSystemObjectType != 1)
{
var link = path;
document.location = link ;
}
});
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
//HTML
<div id="RFQitemtable">
<div id="iteminput">
<div>
<input id="RFQgetFile" type="file">
<input id="RFQaddFileButton" type="button" value="Upload">
</div>
</div>
<br>
<div id="RFQdivraisedocdata">
<table id="RFQtblraisedocdata">
<tr class="titlerow">
<th>File Name</th>
<th>Delete</th>
<th>ID</th>
</tr>
</table>
</div>
</div>
Make TextBox or Dropdown disabled?
$('#suppliername').attr('disabled', true);
Clear TextBox?
$("#ddlSubCategory").val('');
Page Navigation Link/ Redirect to another page
var link = _spPageContextInfo.webAbsoluteUrl + "/Pages/p2pLogin.aspx"
document.location = link ;
Instant added item bind to Gridview and delete Row
$("#tblData").on('click', '.delete-row', function () {
$(this).closest('tr').remove();
});
$(".delete-row").click(function () {
$("table tbody").find('input[name="record"]').each(function () {
if ($(this).is(":checked")) {
$(this).parents("tr").remove();
}
});
});
var objPRItems=[];
$(".add-row").click(function () {
var name = $("#Itemname").val();
var qtys = $("#qty").val();
var Rem = $("#rem").val();
if(name== "")
{
alert("Please Add ItemName");
return;
}
if(qtys == "")
{
alert("Please Add Quantity");
return;
}
if(!qtys.match(/^[0-9]+$/))
{
alert("Invalid Quantity");
return;
}
if(Rem == "")
{
alert("Please Add Remarks");
return;
}
var markup = "<tr><td>" + name + "</td><td>" + qtys + "</td><td>" + Rem + "</td><td><button type='button' class='delete-row' >Delete Row</button></td></tr>";
$("#tblData").append(markup);
// $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
objPRItems.push({"PRItems": { "ItemName": name,
"Qty": qtys ,
"Remark": Rem, }});
$("#Itemname").val("");
$("#qty").val("");
$("#rem").val("");
});
function SaveItems()
{
var stat=false;
var myTab = document.getElementById('tblData');
var name = $(this).children("td:eq(1)").text();
for (i = 1; i < myTab.rows.length; i++) {
var objCells = myTab.rows.item(i).cells;
if (objCells.length > 0) {
var items = objCells.item(0).innerHTML;
var qty = objCells.item(1).innerHTML;
var remark = objCells.item(2).innerHTML;
SavePRItems(items,qty,remark);
}
}
}
function SavePRItems(items,qty,remarks)
{
var returnValue = false;
var currentUserId =_spPageContextInfo.userId;
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var prNumber=$('#prnumber').val();
var budgetRefNo = $('#budgentrefno').val();
if(prNumber == "")
{
alert("PR Number Is Invalid Pls Create New PR")
status = false;
}
if(budgetRefNo == "")
{
alert("budgetRefNo Is Invalid Pls Create New PR")
status = false;
}
var itmName = items;
var qty = qty;
var remark = remarks;
var URL =siteUrl + "/_api/Web/Lists/GetByTitle('PurchaseRequestItems')/Items";
$.ajax
({
url: URL,
type: "POST",
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.PurchaseRequestItemsListItem"
},
//ColumnName:variable name
Title:prNumber,
ItemName:itmName,
Qty:qty,
Remarks:remark,
BudgetrefNo:budgetRefNo
}),
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data, status, xhr)
{
returnValue =true;
},
error: function(xhr, status, error)
{
alert("error...");
}
});
return returnValue;
}
function DeletebeforePRItems(prnumberis)
{
prnumberis= GetParameterValuesApprove();
//var clientContext = new SP.ClientContext(siteUrl);
var clientContext = new SP.ClientContext.get_current();
spList = clientContext.get_web().get_lists().getByTitle('PurchaseRequestItems');
//The Caml-Query
var camlQuery = new SP.CamlQuery();
//camlQuery.set_viewXml('<View><ViewFields><FieldRef Name=" + prnumberis + " /></ViewFields><RowLimit>10000</RowLimit></View>');
camlQuery.set_viewXml(
"<View><Query>" +
"<Where>" +
"<Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">" + prnumberis + "</Value></Eq>" +
"</Where>" +
"</Query></View>");
//get all Items from the list
var collListItem = spList.getItems(camlQuery);
clientContext.load(collListItem);
//Execute the query
clientContext.executeQueryAsync(function () {
var itemCount = collListItem.get_count();
for (var i = itemCount - 1; i >= 0; i--) {
this.oListItem = collListItem.itemAt(i);
this.oListItem.deleteObject();
//Final Delete order
clientContext.executeQueryAsync(function ()
{
//alert('success');
},
function (args)
{
console.log(args.get_message());
//alert('failed');
});
};
});
UpdatePR();
}
HTML,
<div id="itemtable">
<div id="iteminput">
<div id="item"> <span class="titles " > Item</span>
<input type="text" id="Itemname" value="" class="textBox">
</div>
<div id="qtys"> <span class="titles " >QTY</span>
<input type="text" id="qty" value="" class="textBox">
</div>
<div id="remarks" > <span class="titles " >Remarks </span>
<input type="text" id="rem" value="" class="textBox">
</div>
<div id="add">
<input type="button" id="addrow" class="add-row" value="Add">
</div> </div>
<div id="container4">
<table id="tblData">
<tr class="titlerow">
<th>Item</th>
<th>Qty</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</table>
</div>
</div>
CSS:
#itemtable{
width: 800px;
margin-left: 42px;
margin-top: 14px;
padding: 20px;
border: 1px solid black;
}
Delete row of gridview
function deleteRow() {
//deleteRowDeletedClick();
$(this).closest('tr').remove();
$("tblData").on("click", ".delete-row", function () {
$(this).closest('tr').remove();
$(this).parents("tr").remove();
});
$("tblData").find('tr').each(function () {
$(this).parents("tr").remove();
});
}
If droddown slected value Yes / No condition
var sing=$( "#ddlsinglesource option:selected" ).text();
if(sing=="NO")
{
//$("#suppliername").prop("readonly", true);
$('#suppliername').attr('disabled', true);
}
function dateToYMD(dt)
{
var fdt = new Date(dt);
var d = fdt.getDate();
var m = fdt.getMonth() + 1; //Month from 0 to 11
var y = fdt.getFullYear();
fdt = "";
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
var ActualToDateIs = oListItem.get_item('Required_Date');
RequiredDateis = dateToYMD(ActualToDateIs);
var passRequestDateIsis = $("#reqDate").val(RequiredDateis);
var reqDates= $('#reqDate').val();
reqDates= dateToYMD(reqDates);
Get items from sharePoint based on paramter?
function getItembyPRNumber(prnumberis)
{
var clientContext = new SP.ClientContext.get_current();
this.website = clientContext.get_web();
this.listCollection = website.get_lists();
this.oList = listCollection.getByTitle('PurchaseRequest');
var collListItem;
var oListItem;
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
"<View><Query>" +
"<Where>" +
"<Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">" + prnumberis + "</Value></Eq>" +
"</Where>" +
"</Query></View>");
collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Title, ID, Budget_Ref_No, Budget_Coordinator,DSC1Status, Budget_Amount,BuyerStatus, Location, Category, SubCategory, Department, Order_Category, Product_Type, Order_Type, Budget_Category, Desc1, ApprovedBy, RequestDateIs, Created, Author, Required_Date, Recommended_Supplier_Name, SingleSource)');
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
var listItemEnumerator = collListItem.getEnumerator();
while(listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var PrNumberis = oListItem.get_item('Title');
var passPrNumber = $('#prnumber').val(PrNumberis);
Itemidis = oListItem.get_item('ID');
if(DSC1StatusIs != null)
{
DSC1StatusIs = oListItem.get_item('DSC1Status');
}
else
{
DSC1StatusIs = "";
}
if(BuyerStatusis = "Approved")
{
BuyerStatusis= oListItem.get_item('BuyerStatus');
// $('#EditPRsaved').attr("disabled", true);
// $('#Editcanceled').attr("disabled", true);
}
else
{
BuyerStatusis= "";
}
var Createdbyis= oListItem.get_item('Author').$2e_1;
var passCreatedbyis = $('#createdby').val(Createdbyis);
var budgentrefnois= oListItem.get_item('Budget_Ref_No');
var passbudgentrefno = $('#budgentrefno').val(budgentrefnois);
BudgetAmountis = oListItem.get_item('Budget_Amount');
var passBudgetAmountis = $('#budgentamount').val(BudgetAmountis);
//alert(BudgetAmountis);
//var passBudgetAmountisDSC1 = $('#txtbudgetDSC1').val(BudgetAmountis);
Locationdrpis = oListItem.get_item('Location');
//var passLocationis = $('#ddlLocation').val(Locationis);
BindLocationsDropdown();
var recsupllnameis = oListItem.get_item('Recommended_Supplier_Name');
var passrecsupllnameis = $('#suppliername').val(recsupllnameis);
var Desc1is = oListItem.get_item('Desc1');
var passDescis = $("#desc").val(Desc1is);
var ActualToDateIs = oListItem.get_item('Required_Date');
RequiredDateis = dateToYMD(ActualToDateIs);
var passRequestDateIsis = $("#reqDate").val(RequiredDateis);
Categoryis = oListItem.get_item('Category');
BindPageLoadCategorydropdown();
SubCategoryis = oListItem.get_item('SubCategory');
BindPageLoadSubCategorydropdown();
Departmentis = oListItem.get_item('Department');
Teams();
OrderCategoryis = oListItem.get_item('Order_Category');
BindOrderCategorydropdown(prnumberis);
ProductTypeis = oListItem.get_item('Product_Type');
BindProductTypedropdown(prnumberis);
OrderTypeis = oListItem.get_item('Order_Type');
BindOrderTypedropdown(prnumberis);
singleSourceis = oListItem.get_item('SingleSource');
BindSingleSourcedropdown(prnumberis);
BudgetCategoryis= oListItem.get_item('Budget_Category');
BindBudgetCategorydropdown(prnumberis);
GetDSC1Approvers(prnumberis);
//bind textbox cord
var BudgetCordinatoris = oListItem.get_item('Budget_Coordinator').$2e_1;
var BudgetCordinator = $("#BudgetCordinator").val(BudgetCordinatoris);
SetUserFieldValue1(BudgetCordinatoris);
var approver = oListItem.get_item('ApprovedBy').$2e_1;
var papprover = $("#Approvedby").val(approver);
SetUserFieldValueApprover(approver);
GetPRStatusforDisable();
}
}
function errorHandler() {
userDepartment.innerHTML = "Request failed: " + arguments[1].get_message();
}
}
Bind People picker name from list and Bind to DIV id?
code1
function SetUserFieldValue1(userName) {
var idn="BudgetCordinator_TopSpan_EditorInput";
//var _PeoplePicker1 = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId ="BudgetCordinator_TopSpan";
var _PeoplePickerEditer1 = $("input[id='" + idn + "']");
_PeoplePickerEditer1.val(userName);
var _PeoplePickerOject1 = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject1.AddUnresolvedUserFromEditor(true);
}
function SetUserFieldValueApprover(userName) {
var idn="Approvedby_TopSpan_EditorInput";
//var _PeoplePicker1 = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId ="Approvedby_TopSpan";
var _PeoplePickerEditerAppr = $("input[id='" + idn + "']");
_PeoplePickerEditerAppr.val(userName);
var _PeoplePickerOjectAppr = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOjectAppr.AddUnresolvedUserFromEditor(true);
}
Code 2
var BudgetCordinatoris = oListItem.get_item('Budget_Coordinator').$2e_1;
var BudgetCordinator = $("#BudgetCordinator").val(BudgetCordinatoris);
SetUserFieldValue1(BudgetCordinatoris);
var approver = oListItem.get_item('ApprovedBy').$2e_1;
var papprover = $("#Approvedby").val(approver);
SetUserFieldValueApprover(approver);
Code 3
<div id="BudgetCordinator"></div>
Bind Droddown in Page load?
function BindPageLoadCategorydropdown()
{
var returnValue = 0;
var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('PRCategory')/items?$select=*";
$.ajax({
url: apiUrl ,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var selectdesider ="";
var items = data.d.results; // Data will have user object
for (var i = 0; i < items.length; i++)
{
var catogery = items[i].Title;
var id = items[i].ID;
selectdesider = '<option value='+ id +'>'+ catogery +'</option>';
$('#ddlCategory').append(selectdesider);
$("#ddlCategory").each(function () {
$('option', this).each(function () {
if ($(this).text() == Categoryis) {
$(this).attr('selected', 'selected')
};
});
});
}
},
error: function (data) {
returnValue = 0;
}
});
//BindSubCategorydropdown();
return returnValue;
}
code 2:
function UpdatePR()
{
var ds = document.getElementById("ddlCategory");
var CategoryName = ds.options[ds.selectedIndex].text;
var CategoryId = ds.options[ds.selectedIndex].value;
var context = new SP.ClientContext.get_current();
var targetList = context.get_web().get_lists().getByTitle("PurchaseRequest");
this.listItem = targetList.getItemById(Itemidis);
//listItem.set_item('Title', prNumber);
listItem.set_item('Department', TeamName);
listItem.set_item('Order_Category', OrderCategoryName);
listItem.set_item('Required_Date', reqDates);
listItem.set_item('Budget_Ref_No', budgetRefNo);
listItem.set_item('Budget_Amount', budgetAmt);
listItem.set_item('Location', lcname);
listItem.set_item('Product_Type',ProductTypeName);
listItem.set_item('Order_Type', OrderCategoryName);
listItem.set_item('Budget_Category',BudgetCategoryName);
listItem.set_item('Budget_Coordinator',BudgetCordinatorPOC);
listItem.set_item('ApprovedBy',ApproverPOC);
listItem.set_item('Category', CategoryName);
listItem.set_item('SubCategory',SubCategoryName);
listItem.set_item('Status',"Pending");
//listItem.set_item('Team',TeamName);
listItem.set_item('Desc1',descr);
listItem.set_item('SingleSource',single);
listItem.set_item('Recommended_Supplier_Name',supName);
listItem.update();
context.load(listItem);
context.executeQueryAsync(onSystemChildSucceeded(), onSystemChildFailed);
}
}
function onSystemChildSucceeded() {
SaveItems();
BtnSaveUserApprovalHisotory(prnumberis);
//UpdatePRNumber();
alert("PR Request Updated..");
var link = _spPageContextInfo.webAbsoluteUrl + "/SitePages/UserView.aspx";
document.location = link ;
//var link = _spPageContextInfo.webAbsoluteUrl + "/SitePages/PRStageWise.aspx?PRNumber="+prnumberis;
//document.location = link ;
}
function onSystemChildFailed()
{
alert("error occured..");
}
code1
var idn="BudgetCordinator_TopSpan_EditorInput";
//var _PeoplePicker1 = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId ="BudgetCordinator_TopSpan";
var _PeoplePickerEditer1 = $("input[id='" + idn + "']");
_PeoplePickerEditer1.val(userName);
var _PeoplePickerOject1 = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject1.AddUnresolvedUserFromEditor(true);
}
function SetUserFieldValueApprover(userName) {
var idn="Approvedby_TopSpan_EditorInput";
//var _PeoplePicker1 = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId ="Approvedby_TopSpan";
var _PeoplePickerEditerAppr = $("input[id='" + idn + "']");
_PeoplePickerEditerAppr.val(userName);
var _PeoplePickerOjectAppr = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOjectAppr.AddUnresolvedUserFromEditor(true);
}
Code 2
var BudgetCordinatoris = oListItem.get_item('Budget_Coordinator').$2e_1;
var BudgetCordinator = $("#BudgetCordinator").val(BudgetCordinatoris);
SetUserFieldValue1(BudgetCordinatoris);
var approver = oListItem.get_item('ApprovedBy').$2e_1;
var papprover = $("#Approvedby").val(approver);
SetUserFieldValueApprover(approver);
Code 3
<div id="BudgetCordinator"></div>
Bind Droddown in Page load?
function BindPageLoadCategorydropdown()
{
var returnValue = 0;
var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('PRCategory')/items?$select=*";
$.ajax({
url: apiUrl ,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var selectdesider ="";
var items = data.d.results; // Data will have user object
for (var i = 0; i < items.length; i++)
{
var catogery = items[i].Title;
var id = items[i].ID;
selectdesider = '<option value='+ id +'>'+ catogery +'</option>';
$('#ddlCategory').append(selectdesider);
$("#ddlCategory").each(function () {
$('option', this).each(function () {
if ($(this).text() == Categoryis) {
$(this).attr('selected', 'selected')
};
});
});
}
},
error: function (data) {
returnValue = 0;
}
});
//BindSubCategorydropdown();
return returnValue;
}
code 2:
function UpdatePR()
{
var CategoryName = ds.options[ds.selectedIndex].text;
var CategoryId = ds.options[ds.selectedIndex].value;
var context = new SP.ClientContext.get_current();
var targetList = context.get_web().get_lists().getByTitle("PurchaseRequest");
this.listItem = targetList.getItemById(Itemidis);
//listItem.set_item('Title', prNumber);
listItem.set_item('Department', TeamName);
listItem.set_item('Order_Category', OrderCategoryName);
listItem.set_item('Required_Date', reqDates);
listItem.set_item('Budget_Ref_No', budgetRefNo);
listItem.set_item('Budget_Amount', budgetAmt);
listItem.set_item('Location', lcname);
listItem.set_item('Product_Type',ProductTypeName);
listItem.set_item('Order_Type', OrderCategoryName);
listItem.set_item('Budget_Category',BudgetCategoryName);
listItem.set_item('Budget_Coordinator',BudgetCordinatorPOC);
listItem.set_item('ApprovedBy',ApproverPOC);
listItem.set_item('Category', CategoryName);
listItem.set_item('SubCategory',SubCategoryName);
listItem.set_item('Status',"Pending");
//listItem.set_item('Team',TeamName);
listItem.set_item('Desc1',descr);
listItem.set_item('SingleSource',single);
listItem.set_item('Recommended_Supplier_Name',supName);
listItem.update();
context.load(listItem);
context.executeQueryAsync(onSystemChildSucceeded(), onSystemChildFailed);
}
}
function onSystemChildSucceeded() {
SaveItems();
BtnSaveUserApprovalHisotory(prnumberis);
//UpdatePRNumber();
alert("PR Request Updated..");
var link = _spPageContextInfo.webAbsoluteUrl + "/SitePages/UserView.aspx";
document.location = link ;
//var link = _spPageContextInfo.webAbsoluteUrl + "/SitePages/PRStageWise.aspx?PRNumber="+prnumberis;
//document.location = link ;
}
function onSystemChildFailed()
{
alert("error occured..");
}
Get Items from List bind to GridView by SharePoint Rest API?
function BindRFQApprovalHistory(prnumberis)
{
var siteUrl=_spPageContextInfo.siteAbsoluteUrl;
var oDataUrl =siteUrl + "/_api/web/lists/getbytitle('PurchaseRequest')/Items?$filter= Title eq '"+prnumberis+"'";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandlerPageLoad,
error: myErrHandler
});
}
function mySuccHandlerPageLoad(data)
{
try
{
var items = data.d.results;
var fullResults = '<table id="ptblData"><thead><tr class="titlerow"><td id="class10"><b>Role</b></td>' + '<td id="class10"><b>Approval Status</b></td>'+ '<td id="class10"><b>Approver</b></td>' +'<td id="class10"><b>Approved Date</b></td>' + '<td id="class10"><b>Comments</b></td>' + '</tr></thead><tbody>';
for (var i = 0; i < items.length; i++) {
fullResults += '<tr>';
//IDis = items[i].ID;
var role1 = "Buyer";
var BuyerStatusis = "";
var Buyernameis = "";
var BuyerApproveddateis = "";
var Remarksis = "";
//var PrnumberIs2 = items[i].Title;
//var PrnumberIs3 = items[i].Title;
//var PrnumberIs4 = items[i].Title;
//var PrnumberIs5 = items[i].Title;
//var StageWisePRUrl = "PRStageWise.aspx?PRNumber="+PrnumberIs;
//fullResults += '<td id="newclass3"><a id="myLink" title="Clicking" href="'+StageWisePRUrl+'" onclick="return PRLaunch(\''+IDis+'\');">'+PrnumberIs+'</a></td>';
//fullResults += '<td id="newclass2">' + items[i].role + '</td>';
//fullResults += '<td id="newclass2">' + items[i].RequestDateIs + '</td>';
if (items[i].role != null)
{
fullResults += '<td id="newclass2">' + items[i].role+ '</td>';
}
else
{
fullResults += '<td id="newclass2">' + role1+ '</td>';
}
if (items[i].BuyerStatus == "Approved")
{
fullResults += '<td id="newclass2">' + items[i].BuyerStatus+ '</td>';
}
else
{
fullResults += '<td id="newclass2">' + BuyerStatusis + '</td>';
}
if (items[i].BuyerName != null)
{
fullResults += '<td id="newclass2">' + items[i].BuyerName+ '</td>';
}
else
{
fullResults += '<td id="newclass2">' + Buyernameis + '</td>';
}
//var todaysDate = DateThis();
//var dateis = items[i].BuyerApprovedDate;
//currentItem.set_item('thisDate',todaysDate);
if(items[i].BuyerApprovedDate != null)
{
fullResults += '<td id="newclass2">' + items[i].BuyerApprovedDate+ '</td>';
}
else
{
fullResults += '<td id="newclass2">' + BuyerApproveddateis + '</td>';
}
if(items[i].Remarks != null)
{
fullResults += '<td id="newclass2">' + items[i].Remarks+ '</td>';
}
else
{
fullResults += '<td id="newclass2">' + Remarksis + '</td>';
}
fullResults += '</tr>';
}
$('#ptblData').append(fullResults);
//alert('mySuccHandlerPageLoad');
}
catch (e)
{
alert(e.message);
}
}
function myErrHandler(data, errCode, errMessage)
{
alert("Error: " + errMessage);
}
No comments:
Post a Comment