Update status while Drag and drop in sharepoint list - javascript

I have Using Nestable js to drag and drop my list items .and the drag and drop is working fine in UI .but what i need is ,I want to update the status of list items after the item is dropped..How can i achieve this using javascript..
for reference of Nestable js https://codepen.io/Mestika/pen/vNpvVw
Next am retrieving the list items like bellow code
var ListEnumerator = this.myItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
var status = currentItem.get_item('Status');
if (status == "Planned") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridprocess').append(templateString);
}
else if (status == "In Process") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridinprogress').append(templateString);
}
else if (status == "Completed") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridcomplete').append(templateString);
}
else if (status == "Hold") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridincomplete').append(templateString);
}
}
here the li tag is used under
<div class="dd">
<ol class="dd-list" id="gridprocess" >
</ol>
</div>
how can i update the status while drag and drop? please give the code to do it..

Finally I achieved the above question . with the following code...... first i have set on ID to the class name dd as ddprocess like bellow
<div class="dd" id="ddprocess">
<ol class="dd-list" id="gridprocess">
</ol>
</div>
And Next I have Write a function When the id ddprocess is on change i get the Each item id and pass the ID to the Update function
$('#ddprocess').on('change', function () {
// JSON To get the list item in Process
var $this = $(this);
var serializedData = window.JSON.stringify($($this).nestable('serialize'));
// console.log("sData:", serializedData)
// convert the JSON into Object
var obj = JSON.parse(serializedData);
obj.forEach(myFunction);
function myFunction(item, index) {
var eachid = item.id;
// console.log("Item-id", eachid);//you will get id
Updatetoprocess(eachid);
}
});
Next the update function is to Update the status to planned for each item in the ddprocess id .....
function Updatetoprocess(eachid) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var siteurl = "https://abb.sharepoint.com/sites/IAPI-SOP";
var context = new SP.ClientContext(siteurl);
var olistnew = context.get_web().get_lists().getByTitle("TaskList");
var listitem = olistnew.getItemById(eachid);
listitem.set_item('Status', 'Planned');
listitem.update();
context.load(listitem);
context.executeQueryAsync(function () {
alert("Items Updated successfully");
},
function () { console.log("failure") }
)
});
}
Thank you

Related

display all json data with bootstrap card in a dynamic div using jquery

i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});

Show image from byte[] on CSHTML via javascript

I'm creating a timeline page with data from database, and I want to show a image from the object in the View.
The method Get it's working fine, when it returns the var imgSrc receives the data from the byte array converted to base64, but when I try to use the var in the it shows undefinied when I inspect the page.
Someone can give me a hand on how can I solve this?
$.getJSON("../ReportsAuditsTimeLine/GetAuditsResultbyAudit", { AuditID: ID },
function (data) {
var datafromaudit = '';
var div = document.createElement('div');
$('#timeLine').empty();
for (var i = 0; i < data.length; i++)
{
var base64 = "";
var imgSrc = "";
if (data[i].AUDIT_PICTURE != null)
{
//CHECK IMAGE
try {
base64 = Convert.ToBase64String(data[i].AUDIT_PICTURE);
imgSrc = String.Format("data:image/png;base64,{0}", base64);
console.log("Imagem:", imgSrc);
}
catch (Exception) {
}
//END IMAGE
}
if (data[i].AUDIT_ITEM_STATUS == "PASS") {
if (data[i].AUDIT_PICTURE != null) {
datafromaudit += '<li><i class="fa fa-camera bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + '<img src="' + $.imgSrc + '"class="margin" ></img>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
else
{
datafromaudit += '<li><i class="fa fa-pencil-square-o bg-green"></i> ' +
'<div class="timeline-item">' +
'<span class="time">' +
'</span>' +
'<h3 class="timeline-header"><b>ID:' + data[i].ID + " - " + data[i].DESCRIPTION +
'</b></h3>' +
'<div class="timeline-body"> WEIGHT: <b>' + data[i].OD + '</b> STATUS: <b style=color:green;>' + data[i].AUDIT_ITEM_STATUS + '</b>' + ' </div>' +
'<div class="timeline-footer"/>'
'</div></li>'
}
}
}
CONTROLLER
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetAuditsResultbyAudit(string AuditID)
{
var viewModel = new ReportsAuditTimeLineViewModel();
int auditID = Int32.Parse(AuditID);
var auditResults = viewModel.GetAuditsResultbyAudit(auditID);
return Json(auditResults, JsonRequestBehavior.AllowGet);
}
VIEWMODEL
public List<AuditsResultData> GetAuditsResultbyAudit(int AuditID)
{
var list = new List<AuditsResultData>();
var context = new OnlineAuditsEntities();
using (context)
{
var query = from audits in context.tb_Audits
join i in context.tb_AuditItem on audits.AUDIT_ITEM_ID equals i.ID
join a in context.tb_Audit on audits.AUDIT_ID equals a.ID
join s in context.tb_Audit_ItemStatus on audits.STATUS_ID equals s.ID
where audits.AUDIT_ID == AuditID
select new { audits, i,a,s};
foreach (var s in query)
{
var Photo = (from pic in context.tb_AuditPictures
where pic.AUDIT_ID == s.audits.ID
select pic.PICTURE).FirstOrDefault();
if (Photo!=null)
{
list.Add(new AuditsResultData
{
ID = s.audits.ID,
AUDIT_ITEM_ID = s.audits.AUDIT_ITEM_ID,
DESCRIPTION = s.i.SUBCATEGORY_DESCRIPTION,
HASFIND = s.i.HAS_FINDING ?? false,
FINDS = s.audits.FINDINGS ?? 0,
STATUS_ID = s.audits.STATUS_ID,
AUDIT_ITEM_STATUS = s.s.STATUS_DESCRIPTION,
OD = s.audits.OD ?? 0,
COMMENTS = s.audits.COMMENTS,
SCANS = s.audits.SCANNED_CODE,
AUDIT_ID = s.audits.AUDIT_ID,
AUDIT_PICTURE = Photo
});
}
}
}
return list;
}
You should pass picture to view as Base64String from controller. Then convert it to picture like:
var picture = "data:image/jpg;base64," + data.base64image;

Make a list with multiple pages in Jquery

I'm making a page with a list of products (which are loads using ajax) but i want to show only 6 products/page but i don't know how to do it and i don't find any examples that implements what i want. So for example if i have 20 products i want to show 6 in the first page, 6 in the second, .. etc to the last product in the last page (the page is always the same only the products change).
So in the end of the page i must have page 1-n
Can someone help me?
this is the js that load the products and show them one below the other:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "json/projects.json",
dataType: "json",
success: function (data) {
showInfo(data);
},
});
});
function showInfo(data) {
var htmlString = "";
if (data.length == 0) {
htmlString =
"<span id = " +
"message>" +
"Non รจ stato trovato alcun progetto" +
"</span>";
$("#list").append(htmlString);
} else {
//altrimenti stampo data
for (i = 0; i < data.length; i++) {
//scorro tutto il mio file json
htmlString =
"<div class = " + "project id = " + data[i].id + ">" +
"<div class =" + "row-list>" +
"<div class = " + "title>" + data[i].title + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/user.png>" + data[i].username + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/budget.png>" + data[i].budget + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/data.png>" + data[i].data + "</div>" +
"<div class = " + "flag>" + data[i].flag + "</div>" +
"</div>";
// collego al div #list le informazioni
$("#list").append(htmlString);
}
// aggiungo l'handler per visualizzare i dettagli quando un progetto viene cliccato
$(".project").click(function () {
window.location.href = "details.php?id=" + $(this).attr("id");
});
}
}
If the page doesn't change, you can stay on the same page while simply changing the products shown.
Here's a simplified version to demonstrate how this could work:
// create 20 product names
let products = [];
for (let i=1; i<=20; i++) {
products.push(`This is Product Name ${i}`);
}
let firstShown = 0;
const display = document.getElementById('display');
// display up to 6 products on page
function addToDisplay(first) {
display.innerHTML = '';
let last = Math.min(first+5, products.length-1);
for (let i = first; i <= last; i++) {
let li = document.createElement('li');
li.innerHTML = products[i];
display.appendChild(li);
}
}
function forward () {
display.innerHTML = '';
firstShown += 5;
addToDisplay(firstShown);
}
function back () {
display.innerHTML = '';
firstShown = Math.max(firstShown-5, 0);
addToDisplay(firstShown);
}
// show initial 6 producs
addToDisplay(firstShown);
<p>Display multiple products 6 at a time<br/>
<button type="button" onclick="back();">Back</button>
<button type="button" onclick="forward();">Forward</button>
</p>
<ul id="display"></ul>

Dynamic select drop down box returning null or undefined

I am trying to achieve a dropdown box in my webpage which lists the options from the values in the database. I have achieved showing the listed options for the dropdown, but when I select the option it is not set to a value. In other words I have a doubt whether my dropdown is initialized or not.
I have added the required snippet for the action.
function add_row() {
table = document.getElementById('b_book');
var rowData = document.createElement('tr');
rowData.innerHTML = '<td>' + slno +
'</td><td id="dbSNO"><select id="SNO[' + slno + ']" onchange="detail_fetcher(this.value)" onselect="detail_fetcher(this.value)" onload="detail_fetcher(this.value)"></select></td>' +
'<td id="dbLNO"><input type="text" id="LNO[' + slno + ']" list="lot_srch_list" onkeydown="LNO_COL(event,this.value,this.id)" onfocus="lotNo_select()"/></td>' +
'<td><input type="text" id="dbMTR[' + slno + ']"/></td><td id="dbWT[' + slno + ']"></td><td id="dbMWT[' + slno + ']"></td><td id="GPM[' + slno + ']"></td><td id="dbTONE[' + slno + ']"></td><td><button id="btn_rem[' + slno + ']" onclick="remove_row()">Remove</button></td>';
table.appendChild(rowData);
slno += 1;
}
function LNO_COL(e, lno, hashtag) {
var beg_pos = hashtag.indexOf('[') + 1;
var end_pos = hashtag.indexOf(']');
var hash_pos = hashtag.substring(hashtag.lastIndexOf('[') + 1, hashtag.lastIndexOf(']'));
var postIN = 'par=' + parname.value + '&lno=' + lno;
if (e.ctrlKey) {
sNo_list = document.getElementById('SNO[' + hash_pos + ']');
sNo_list.innerHTML = '';
var XMLhLNO = new XMLHttpRequest();
XMLhLNO.onreadystatechange = function () {
if ((this.readyState === 4) && (this.status === 200)) {
var result = this.responseText;
var JSON_result = JSON.parse(result);
for (z in JSON_result) {
var sno_opt;
sno_opt = document.createElement('option');
sno_opt.value = JSON_result[z].slno;
sno_opt.text = JSON_result[z].slno;
sNo_list.appendChild(sno_opt);
}
}
};
XMLhLNO.open('POST', 'sno_lot_par2.php', true);
XMLhLNO.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
XMLhLNO.send(postIN);
detail_fetcher(hashtag);
}
}
function detail_fetcher(hash_position) {
var row_no = hash_position.substring(hash_position.lastIndexOf('[') + 1, hash_position.lastIndexOf(']'));
var serial_row = document.getElementById('SNO[' + row_no + ']');
alert(serial_row.);
/* var XMLfetcher = new XMLHttpRequest();
XMLfetcher.onreadystatechange = function()
{
if((this.readyState == 4)&&(this.status == 200))
{
var src_result = this.responseText;
var JSON_res = JSON.parse(src_result);
alert(serial_row_db);
alert(src_result);
}
};
XMLfetcher.open('POST','srch_lot2.php',true);
XMLfetcher.setRequestHeader('Content-type','application/x-www-form-urlencoded');
XMLfetcher.send(('row=' + serial_row_db));
*/
}
I have tried using value method, selecteditem(index) method but none of them proves to be successful.
Note: I want to use pure JavaScript as I am quite confused with using jQuery.

Why can't I update this table with the same code used in another place using Javascript?

The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>&nbsp&nbsp&nbsp&nbsp<button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>&nbsp&nbsp&nbsp&nbsp&nbsp<button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)

Categories

Resources