Displaying Column Description on Hover - javascript

I would like to display the column description of my sharepoint list when the user hovers the mouse over the column header. Currently there is no out of the box solution for this and I followed this guide. However this guide does not work for SharePoint 2013. Any help or direction would be helpful!
Here is the list view that I am trying to apply this to.

The exact steps depend on if you plan to use a Content Editor web part or directly edit the View page. Let me know if you aren't sure how to do either.
The result:
The JavaScript:
Notes: Use the jQuery library version of your choice. Change the "Tickets" list name to your list name.
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
var testresults
function test() {
var headings = document.getElementsByClassName('ms-vh-div')
for (var i=0;i<headings.length; i++)
{
var columnName = headings[i].getAttribute("name");
columnName = columnName.replace("_x0020_"," ");
var head = headings[i].getElementsByTagName('a')[0];
//head.title = head.title + "\nhello world"
$.ajax({
"url": _spPageContextInfo.webServerRelativeUrl +
"/_api/web/Lists/getbytitle('Tickets')/fields?$select=Description&$filter=Title eq '" + columnName + "'",
"method": "GET" ,
"theHeading": head,
"headers": {
"accept": "application/json;odata=verbose"
},
"success" : function(data) {
var xml = arguments[2].response;
var description = "" + $(xml).find("content").text()
this.theHeading.title += "\n" + description;
},
"error" : function(e) { console.log("error " + e.message) }
});
}
}
// delay script until SharePoint "stuff" is finished.
_spBodyOnLoadFunctionNames.push("test")
</script>

Related

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

Duplication in HTML datalist using JQuery with more than one clicks

I design a datalist on web page. And I want to fill this datalist using JQuery. Controller execute a query and get a list of facilities. Then pass this list to client side. This datalist can show all the facilities. When user click this textbox, the facilities will be listed in drop down list. But when user click more than once, there will be duplicates in datalist. That means, if you click twice, the result will be shown twice in datalist.
Here is code in MVC view
datalist:
<input type="text" list="facility" autocomplete="on" name="Facility" id="facilities" />
<datalist id="facility"></datalist>
JQuery Code:
$(document).ready(function () {
$('#facilities').click(function () {
//alert("Clicked");
var postData = $('#clientTxt').val();
$.ajax({
type: "POST",
url: '#Url.Action("FacilityCheck", "PCA")',
data: { clientTxt: postData },
success: function (result) {
//successful
for (var i = 0; i < result.facilities.length; i++) {
//alert(JSON.stringify(result.facilities[i]));
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
//I want to add an if judgement to avoid duplicates here
//Like contains() method in JAVA.
$('#facility').append(option);
}
},
error: function (result) {
alert('Oh no :(');
}
});
});
});
The duplicates image after clicking many times:
So please give me some advice. Thanks a lot!
It is because you are using the jQuery append() method and not replacing the HTML. Right now, you're just adding (appending) to it every time you iterate through your loop of result.facilities[i] instead of replacing the content.
Your best bet would be to add all of that source to a string and replace the $('#facility')'s innerHTML with the new content. You can use $('#facility').html(yourContentString); to do so.
Hope this helps!
For example...
success: function (result) {
var options = "";
//successful
for (var i = 0; i < result.facilities.length; i++) {
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
options = options + option;
} //end of loop
$('#facility').html(options); // replace the innerHTML of #facility with your new options string
},
Simply modify your success like this :
$('#facility').html('');
$('#facility').append(option);
Remove the items before appending them.
You can also use empty :
$('#facility').empty();

couchdDB dbroot issue

I am using couchdb. I am new to it. I don't know what to have in dbroot value in place of "db/". I have taken this code from one of coucdb tutorial.
Thanks in advance for your help.
//Use a namespace to protect the scope of function and variable names
var poq = {
//Some variables global to the local namespace ("poq")
root: "http://localhost:5984/",
dbroot: "db/",
max_quotes: 6,
//Invoked when the HTML page is first loaded
loadPage: function()
{
var six_latest = poq.root + "poquotes/_design/document/_view/by_year?&limit="
+ poq.max_quotes + "&descending=true&callback=?";
$.getJSON(six_latest, poq.handleMainQuotes);
$('#donewquote').click(function() {
var db_link = poq.dbroot + "poquotes";
var record = {
"type": "quote",
"author": $("#author").val(),
"text": $("#text").val(),
"work": {
"title": $("#title").val(),
"link": $("#link").val(),
"year": parseInt($("#year").val())
}
};
$.ajax({
url : db_link,
data : JSON.stringify(record),
contentType : "application/json",
type : 'POST',
processData : false,
dataType : "json",
success : function(resp) {
alert("New document created: " + JSON.stringify(resp));
}
});
return false;
});
//Set up the collapsible form for adding new quotes
$('#popup').click(function(){
$("#newquote").slideToggle();
});
//Start out with the create quote form collapsed
$("#newquote").slideToggle();
},
//Invoked with the result of the AJAX call to load quote documents
handleMainQuotes: function(json)
{
//Load up to six records, as available
quote_count = Math.min(poq.max_quotes, json["total_rows"])
for (var i=0; i<quote_count; i++) {
var doc = json["rows"][i]["value"]
var year = doc["work"]["year"].toString()
var title = doc["work"]["title"].toString()
var link = doc["work"]["link"].toString()
//Create an HTML snippet from the fields of each quote document
qblock = $("<div class='span4 featured-quote'></div>")
.append("<h2>" + doc["author"] + "</h2>")
.append("<p style='font-size: 80%; height: 8em;'>" + doc["text"] + "</p>")
.append("<p>" + year + "</p>")
.append("<p><a href='" + link + "'>" + title + "</a></p>")
.append("<p><a class='btn' href='#'>View details ยป</a></p>")
//jQuery's eq selector to find the target div corresponding to the loop index
$('div.featured-quote:eq(' + i.toString() + ')').replaceWith(qblock);
}
},
}
Looks like dbroot here is meant to be the name of your database. If you haven't created a database yet, you can do so with:
curl -X PUT http://localhost:5984/mynewdatabase
Being new to CouchDB I recommend you start with The Definitive Guide (http://guide.couchdb.org)

Seeing span tag when I want to be rendering the text within the span tag

I have some words on a page that display "present" or "absent" that a user can click to toggle between being present or absent.
When the word is set to "absent" I want that text to be red.
The word represents a bool and is updated on screen using the following code:
<script type="text/javascript">
absentText = $.trim('#MyApp.Resources.MyAppResource.Absent_Text').toLowerCase();
presentText = $.trim('#MyApp.Resources.MyAppResource.Present_Text').toLowerCase();
updateAttendanceUrl = '#Url.Action("UpdateAttendance", "Attendance")';
</script>
Where MyAppResource.Absent_Text = absent the page displays fine with the word, "absent" on the page.
When I change MyAppResource.Absent_Text to read "absent" my page literally displays <span style="color:red">absent</span>
Here is a sample of my view source:
<td><span style="color:red">absent</span></td>
So somehow my < and > symbols are getting taken away.
How can I change my code so that when the word on my screen is written as "absent" it is colored red?
Is there a simpler way to just color any text on the screen that matches "absent" red?
For reference, here is the rest of the javascript from my page:
var userId;
var attendanceDay;
var isPresent;
var updateAttendanceUrl;
var absentText;
var presentText;
var courseId;
$(document).ready(function (event) {
$('.attendance').live('click', function () {
userId = $(this).parents('tr').attr('id');
if (userId != '') {
attendanceDay = $(this).attr('id');
isPresent = $.trim($(this).find('span').text().toLowerCase());
courseId = $(this).parents('tbody').attr('id');
$(this).find('span').addClass('currentClass');
if (isPresent == absentText) {
UpdateAttendance(1);
} else {
UpdateAttendance(0);
}
} else {
event.preventDefault();
}
});
});
function UpdateAttendance(present) {
url = updateAttendanceUrl;
$.ajax({
type: "POST",
url: url,
data: "userId=" + userId + "&attendanceDay=" + attendanceDay + "&courseId=" + courseId + "&present=" + present,
success: function (data) {
if (isPresent == absentText) {
$('#' + userId).find('.currentClass').text(presentText).removeAttr('class');
} else {
$('#' + userId).find('.currentClass').text(absentText).removeAttr('class');
}
return true;
}
});
}
What your looking for is called unescape or htmldecode. There are various topics available on SO already. Here is one.

Removing HTML code from a javaScript array?

Hi I have the following code in a javaScript file called songs:
var marchMD = new Array();
marchMD[0] = ["Save the Best for Last - Vanessa Williams"];
marchMD[1] = ["Informer - Snow"];
marchMD[2] = ["The Sign - Ace of Base"];
for (var i=0;i<marchMD.length; i++) {
songList = songList + '<p>' + marchMD[i] + '</p>';
}
$('#songs').html(songList);
Once this has been loaded, the follow javaScript in the file youtube reacts with the code above:
$(document).ready(function() {
$('#songs p').click(function(e) {
var $el = $(e.currentTarget);
var search = $el.html();
//alert(search);
//return;
var keyword = encodeURIComponent(search);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type:"GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i, data) {
var video_id = data.id;
var video_frame = "<iframe width='420' height='315' src='http://www.youtube.com/embed/" + video_id + "' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").hmtl("<div id='no'> No Video</div>");
}
}
});
});
});
The alert that I have in the code above was a test to see if it would return anything and it doesn't. However, if I remove the href html tag from the code this works. The reason I have it is so when someone clicks one of the songs, it takes them to the top of the page to view that song in youtube.
Thanks
If you know that the element that contains your link will only ever contain your link, you could use text() to strip out the HTML formatting, like this:
var search = $el.text();
When you have the <a> in there, var search = $el.html(); includes the tag as well, not just the text. Try this:
$('#songs p').click(function(e) {
var search = $(this).find('a').html();

Categories

Resources