Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 13 September 2018

Multi line column data Format issue in Document Library SharePoint

Recently, we need to show data from Document library to a classic view page. We get rest call. Get data. Display on page. Task done. Easy right? No. There was a multi line column which was showing data as row text. Also that column has 255 character limit. How can this be?

Analysis:
We got a tech net page which says multi line is not same in list and library. So we won't get rich text or enhance rich text option in that. Only plain text available.

Reference - https://social.msdn.microsoft.com/Forums/office/en-US/67a70245-cd03-48e1-b0fa-71bbb6a7744d/is-enhanced-rich-text-column-supported-by-document-library?forum=sharepointcustomizationlegacy

Solution:

So there were two issue. And below are solution for same:


  • Getting 255 character limit.
So open column and set settings to allow unlimited text. It will fix this issue.




  • Show multi line data as formatted.
For this you need to use "<Pre>"tag. It will show data in same way the text is entered in column.

Code sample:



$(document).ready(function(){
$.ajax({     
url:_spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getByTitle('Newsletter')/items?$select=DocIcon,EncodedAbsUrl,FileLeafRef,Editor/Title,Highlighted_x0020_Content&$expand=Editor&$orderby=FileLeafRef desc",
    type: "GET",  
    headers: {  
        "accept": "application/json;odata=verbose",  
        "content-Type": "application/json;odata=verbose"  
    },  
    success: function(data) {  
var html="";
for(i=0;i<data.d.results.length;i++){
var currentData = data.d.results[i];
var previewPath = _spPageContextInfo.webAbsoluteUrl +"/_layouts/15/getpreview.ashx?path="+ currentData.EncodedAbsUrl;
var highlightedContent = currentData.Highlighted_x0020_Content!= null ? currentData.Highlighted_x0020_Content:"";
var docType = currentData.DocIcon;
var imgdoc;
        html+="<div class='parentDiv'><div class='titleDiv'>"+currentData.FileLeafRef+"</div><div class='editDiv'></div><div class='contentDiv'><pre>"+highlightedContent +  "</pre></div></div>";
}
$("#NewsLetter").html(html);
    },  
    error: function(error) {  
        console.log(JSON.stringify(error));  
    }  
}); 
})

Thursday, 3 September 2015

Find element using jQuery.

If you want to find html element using jquery this post can be helpful.


  • If you're finding by Contains then it'll be like this

    $("input[id*='ElementID']")

  • If you're finding by Starts With then it'll be like this

    $("input[id^='ElementID']")

  • If you're finding by Ends With then it'll be like this

     $("input[id$='ElementID']")

  • If you want to select elements which id is not a given string

    $("input[id!='ElementID']")

  • If you want to select elements which id contains a given word, delimited by spaces

     $("input[id~='ElementID']")

  • If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='ElementID']")

Friday, 31 July 2015

Responsive Design

Increase of portable device usage requiring dynamic design changes for static site. Currently I have faced some issue with such concept. My requirement was to display a table on a page and make it look dynamic.

Here are some methods that I used to do it.

1) Using pure CSS :

You need to use media queries to make content dynamic. here is my code sample:

// for device Apple iPhone 5 or less, Samsung Galaxy S3 mini or less and Microsoft Lumia phones
@media (max-width: 320px) {
#docsTable{ 
max-width:320px;
}
}

// for device Apple iPhone 6,LG G3,LG Optimus G,Samsung Galaxy Note 2,Samsung Galaxy S3- S5,Samsung Galaxy Nexus

@media (max-width: 480px) {
#docsTable{ 
max-width:480px;
}
}

//for Apple iPad series
@media (max-width: 768px) {
#docsTable{ 
max-width:768px;
}
}

For other device width information  click here

But the problem occurs when the device has slightly smaller or larger width. It displays scroll which is not user friendly. Here is a way to handle such thing:

2) using Javascript

In this method we calculate the width by device's width and add width css to control at display time.

<script type="text/javascript">
$(document).ready(function() {
    // run test on initial page load
    checkSize();

    // run test on resize of the window in browser. Also need for screen rotation.
    $(window).resize(checkSize);
});

//Function to the css rule
function checkSize(){
    if(window.innerWidth < 768)
{
var thisObject = $("#docsTable");
var actualWidth = window.innerWidth - 50;
thisObject.css("max-width",actualWidth+"px");
}
});
}
</script>

Monday, 6 July 2015

Display Other site collection List data in current site collection using Client object modal.

A very bad dream in SharePoint 2013 is to "Display Other site collection List data in current site collection" as SharePoint Designer 2013 has deprecated data view web part and content search web part does not give look and feel as we wanted. It might be simple but I will update my self and this blog if I get success in near future with it.

Here is the sample code to display data from other site collection:

1) You need to add a web part page.  Add a "Content Editor Web part " in this page. In this paste below code with your changes.

<div>
   <!-- Table -->
  <table id="docsTable">
    <thead>
    <tr>
<th>ID</th>
<th>Title</th>
<th>Modified</th>
</tr>
</thead>
  </table>
</div>


<script language="javascript" type="text/javascript">
$(document).ready()
{
var folderUrl = document.getElementById('folderpath').value;
var url =document.getElementById('sitepath').value +"/_api/Web/GetFolderByServerRelativeUrl('" + folderUrl + "')?$expand=Folders,Files";


 // Get Folders and Files in single call. You can try using ajax call too. I have tried it but I was forced to call method multiple time.

$.getJSON(url,function(data,status,xhr){

 // Get Folders

    for(var i = 0; i < data.Folders.length;i++){      
        $('<tr>').append(
        $('<td>').html("data.Folders[i].ID"), // Append ID
        $('<td>').html("<a href='"+data.Folders[i].ServerRelativeUrl+"' target='_blank'>"+data.Folders[i].Name+"</a>"), // Apend Name. Click redirect to specific Item
        $('<td>').text(data.Folders[i].TimeLastModified.substring(0, 10))).appendTo('#docsTable'); //Append modified date.
    }

 // Get Files

    for(var i = 0; i < data.Files.length;i++){      
        $('<tr>').append(
        $('<td>').html("data.Files[i].ID"),  // Append ID
        $('<td>').html("<a href='"+data.Files[i].ServerRelativeUrl+"' target='_blank'>"+data.Files[i].Name+"</a>"), // Apend Name. Click redirect to specific Item
        $('<td>').text(data.Files[i].TimeLastModified.substring(0, 10))).appendTo('#docsTable');//Append modified date.
    }
})

}

This is a sample code. You can Add some more functionality like paging, sorting or can change fields as per your need.

JavaScript check if file exist at URL or not.

I was trying simple things lately with client side object modal. Here is one of the main issue I have face

"How to check if image / file exist at given path?"

I have tried using .done,.fail,.success,.complete and many more tricks that I could use. Even I tried Try.. Catch .. finally. But the real issue was if file does not exist at URL it will give exception 404. But not throw it so it won't be cached. Finally I came across a method shown below which gives me 404 error but will return result.

Answer: 

function doesFileExist(urlToFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send(); // Here it will generate 404
   
    if (xhr.status == "404") {
        return false;
    } else {
        return true;
    }
}

Calling :

if (doesFileExist(filePath)) {
            // yay, file exists!
        } else {
   // oops, file not exist!
}

Monday, 25 May 2015

Service error - "Memory gates checking failed because the free memory (xxxxx bytes) is less than 5% of total memory."

I was testing few service scripts when I encounter with this error -

"Memory gates checking failed because the free memory (xxxxxxxxx bytes) is less than 5% of total memory."

Resolution:

Adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element or your project config file.

The easiest way just add this into your web.config

<system.serviceModel>
<serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />

</system.serviceModel>

Reference:
1) http://support.ge-ip.com/support/index?page=kbchannel&id=23301025e79bf210148caf0ad63007ec5
2) http://stevemannspath.blogspot.in/2012/07/sharepoint-2013-opening-memory-gates.html

Wednesday, 6 May 2015

SharePoint Idle timeout for windows user.

Recently i was working on sign out idle user after certain minutes. After so much tiresome tries i was able to generate a JavaScript that log out windows authenticated user in each browser.

Here is the code that you need to add in master page.

var IDLE_TIMEOUT = 30*60; //seconds - need to sign out if idle for 30 min.
        var _idleSecondsCounter = 0;
        document.onclick = function () {
            _idleSecondsCounter = 0;
        };
        document.onmousemove = function () {
            _idleSecondsCounter = 0;
        };
        document.onkeypress = function () {
            _idleSecondsCounter = 0;
        };
        window.setInterval(CheckIdleTime, 1000);//milliseconds (1 sec = 1000 millisecond) check every 1 second for idle timeout

        function CheckIdleTime() {
            _idleSecondsCounter++;
           
            if (_idleSecondsCounter >= IDLE_TIMEOUT) {
                document.location.href = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl + "/_layouts/15/closeConnection.aspx?loginasanotheruser=true?Source=";
            }
        }

Thursday, 11 September 2014

javascript keypress event

Sometimes we need to handle enter key event on textbox. For that we can use fiollowing code

    $('#myInput').keypress(function(event) {
        if (event.keyCode == 13) {
            alert('Entered'); // write your code here
        }
    });

myInput : textbox/ input control id
event.keyCode : The e key value you needed.
Here are some key values:
Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
Key Code
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
Key Code
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222