Requirement:
Place a drop down control named Language on a page and load list of languages from a SharePoint list.
Solution:
In SharePoint site, create a page. Insert Content Editor web part and place a div tag as below:
<div id="LanguageDrp"></div>
Place following script in a .js file and load the JS file from the page.
-------------------------------------------
var currLang = "";
function getLanguageList()
{
$("div#LanguageDrp").html("" );
$.ajax({
type: "GET",
async:"true",
contentType: "application/json;odata=verbose",
headers: { "Accept": "application/json; odata=verbose" },
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Language%20Filter')/items?$select=Title&$orderby=Order0",
success: function(data){
var htmlLang = "";
htmlLang += "<table cellpadding='5' cellspacing='5' style='width:60%'>";
htmlLang += "<tr><td style='color:black;font-weight:bold'>Language</td><td><select id='selLang'>";
$.each(data.d.results, function(index, item){
if(currLang == item.Title)
{
htmlLang +="<option selected value='"+item.Title+"'>"+item.Title+"</option>";
}
else
{
htmlLang +="<option value='"+item.Title+"'>"+item.Title+"</option>";
}
});
htmlLang += "</select></td></tr>";
htmlLang += "</table>";
$("div#LanguageDrp").html(htmlLang );
$("div#LanguageDrp").closest('td').show();//css("display","block");
$("div#LanguageDrp").closest('td').parent().css("width","100%");
$("div#LanguageDrp").parent().parent().css("background","transparent");
$('#selLang').change(function() {
var url = window.location.href;
if (url.indexOf("?")>-1)
{
url = url.substr(0,url.indexOf("?"));
}
if(getParameterByName("Roles")!=null)
{
window.location.replace(url + "?Roles="+ getParameterByName("Roles")+ "&lang=" +$(this).val() );
}
else if(getParameterByName("Related%20Topic")!=null)
{
window.location.replace(url + "?Related%20Topic="+ getParameterByName("Related%20Topic")+ "&lang=" +$(this).val() );
}
else if(getParameterByName("Region")!=null)
{
window.location.replace(url + "?Region="+ getParameterByName("Region")+ "&lang=" +$(this).val() );
}
else
{
window.location.replace(url + "?lang=" +$(this).val() );
}
});
},
error: function(data){
$("div#LanguageDrp").html("<span style='color:red'><b>Unable to get Language Filter - Refresh the page to try again or contact Administrator </b></span>");
} });
}
$(document).ready(function()
{
$("div#LanguageDrp").html("");
if(getParameterByName("lang") == null)
{
currLang = "English";
}
else
{
currLang = getParameterByName("lang");
}
getLanguageList();
});
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^]*)",
regex = new RegExp( regexS ),
results = regex.exec( window.location.href );
if( results == null ){
return null;
} else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
No comments:
Post a Comment