I'm using now.js with nano (CouchDB library) to fill a select with options.
Server:
everyone.now.getThings = function(thing) {
var self = this;
return db.view('lists', 'some_things', function(error, data) {
var list = data.rows.map(function(obj) {
return '<option value="' + obj['id'] + '">' + obj['value'] + '</option>';
});
return self.now.receiveThings(list);
});
};
Client:
$(document).ready(function() {
now.getThings($('select#thing').val());
$("#poke").click(function() {
now.getThings($('select#thing').val());
});
});
On the client it says for the first call "TypeError: 'undefined' is not a function". Within the .click()-Function everything works fine.
now.js is loaded before application.js. I tried $(now).ready() as well, but it didn't work.
What's the problem?
I solved the problem by including the first set of data in the jade template call and created a .change()-handler on the select.
Related
I'm have trouble accessing json data within the console. If for instance I wanted to type in courses[0].name or courses.length, I get the error "courses is not defined". I'm definitely missing something here but I'm unsure how to go about it. The list is generating just fine on the DOM, but I want want to access specific parts within the array.
$(document).ready(function () {
var showData = $('#show-data');
$.getJSON('../undergraduate/ug.json', function (data) {
console.log(data);
var courses = data.courses.map(function (course) {
return course.code + ': ' + course.name;
});
if (courses.length) {
var content = '<li>' + courses.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
});
<body>
Get JSON data
<div id="show-data"></div>
</body>
The json data also seems to be appearing fine initially on load within the console log:
Any help would be very appreciated. Thanks in advance!
I have an external list in SharePoint that includes a URL column. The URL column is a calculated field in SQL server, so the entire URL is already there. I need this field to hyperlink and I have been trying to use JSLink to do so. What would the JavaScript for that look like?
For example, if my fields were...
First Name | Last Name | Profile URL
How would I get the URL in the Profile URL field to hyperlink?
I have been looking for solutions all morning without any luck. I am not familiar with JavaScript, so the code I am using is pieced together from posts I have been reading. I have made sure the my JSLink address is correct.
~site/SiteAssets/myCode.js
I have tried different variations of code. My latest is this:
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"Profile_X0020_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema["Profile_X0020_URL"]];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();
After applying my JSLink to my web part I reload the page and nothing happens. No errors but no links.
I'm also not sure how to reference the column. In SQL Server it is PROFILE_URL, but in the SharePoint list header it is Profile URL.
Modify the code as below to check if it works.
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"PROFILE_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();
I currently have a servlet setup to send over a list of our active servers. The method grabs the servlet data, processes it, then injects the html into the datalist tag. HTML injection process works, but when I'm splitting the array by the concat separator (which I've done before), I get no values. Below I'll explain with code examples:
HTML:
<label for="server_id_text">Server ID: </label>
<input id="server_id_text" list="server_names" name="server_id" required>
<datalist id="server_names">
<!--This gets injected with the active servers grabbed through a get request-->
</datalist>
Javascript connecting to server to get data:
Note: serverList is a global variable.
var serverList = "";
function setupAutoComplete() {
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
console.debug("server list auto comp at post mailing: " + serverList);
});
}
This method is called in the function that is called when the onload event is called in the body tag
Here are the two methods that inject the html:
function setupServerName() {
document.getElementById("server_names").innerHTML = getServerListHTML();
}
function getServerListHTML(){
console.debug("Autocomplete process running...");
var servArr = String(serverList).split('*');
var html = '';
var temp = '<option value="{serverName}">';
console.debug("Array:" + servArr.toString());
if (serverList == 'undefined' || servArr.length == 0){
console.debug("serverList is empty...");
return '';
}
for (var i =0; i < servArr.length; ++i){
html += temp.replace("{serverName}", servArr[i]);
}
console.debug("html: " + html);
console.debug("ServList size " + servArr.length);
return html;
}
When the page loads, setupAutoCompelte() is called first. Then, setupServerName() is called.
My issue is that after I load the page, I get the correct response from the server. For instance, I'll get server1*server2 as a response to the jQuery $.get(...) call. Then I go to split the string into an array, and I get back an empty html tag (<option value="">);
Also, the debug console info are as follows:
Autocomplete process running...
Array:
html: <option value="">
ServList size 1
Status with auto comp id: success
server list auto comp at post mailing: server1*server2
Thanks for the help!
I believe that your setupServerName() function is being called before the AJAX request in setupAutoComplete() returns, so your serverList is an empty string at that point. What you need to do is populate your <datalist> from inside your AJAX callback in setupAutoComplete().
// setup autocomplete datalist
function setupAutoComplete() {
var $datalist = $('#server_names');
$.get(baseURL + '/SupportPortal').then(function (data) {
// update datalist
if (!data || !data.length) {
// no servers, empty list
$datalist.html('');
} else {
// create options html:
// reduce array of server names
// to HTML string, and set as
// innerHTML of the dataset
$datalist.html(data.split('*').reduce(function (html, server) {
return html + '<option value="' + server + '">\n';
},''));
}
});
}
// on page load, setup autocomplete
$(function () {
setupAutoComplete();
});
As you can see from "debug console info":
the get function is asyncrhonous so you need to change your setupAutoComplete get part to:
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
setupServerName();
console.debug("server list auto comp at post mailing: " + serverList);
});
On page load try to call directly the setupServerName function within the success event of get function. A different approach is to divide the setupServerName function so that the part related to the serverList variable becomes part of another function.
The serverList variable is global but its content is filled after the setupServerName is executed.
I am using a javascript Get call to grab the json data for a collection I created in deployd. I got this code directly from the deployd backend. It gives me a json array that is put into the console, but I am far from figuring out how to parse the json not sure if thats the right term, and output it into seperate p tags for each item within in the collection.
I also have included jQuery and I am assuming based on what I have looked into online that it makes it much easier to do so. Also if there is a better library than jQuery to learn to do this with, or something that makes more sense for deployd lets say Angular, I would love to be steered in the right direction.
Here is the javascript get request provided.
dpd.things.get(function (result, err) {
if(err) return console.log(err);
console.log(result);
});
I have tried looking at a example app off the deployd site to see how they did it but havent quite figured it out here is my failed attempt below
<body>
<h1>Welcome to Deployd!</h1>
<p>You've just created a Deployd app. You can add front-end files in the <code>public</code> folder.</p>
<p>If you're new to Deployd, have a look at the Getting Started Guide or <a href="http://docs.deployd.com/docs/getting-started/your-first-api.md">Hello World Tutorial<a>.</p>
<p class="hide" id="empty">You don't have any todos! Add one now:</p>
<ul id="todos" class="unstyled"></ul>
</body>
<script>
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
// $label = $('<label class="checkbox">')});
$el.appendTo('#todos');
$('#empty').hide();
}
</script>
NEW RECCOMENDED CODE NOT WORKING
function getTodos() {
// Get all todos
dpd.things.get(function(result, err) {
if (err) {
// Alert if there's an error
return alert(err.message || "an error occurred");
}
if (!result.length) {
$('#empty').show();
}
// todos is an array
result.forEach(function(thingy) {
renderTodo(thingy);
});
});
}
function renderTodo(thingy) {
var $el = $('<li>');
$el.text(thingy);
$el.appendTo('#todos');
$('#empty').hide();
}
Here is the site running on localtunnel so you can see the console. https://twig.localtunnel.me
Try adding 'thingy' in the code so it will display the items returned from the collection; Just make sure a collection is being returned.
If thingy is plain text:
var $el = $('<li>')
$el.text(thingy);
If thingy includes html with text:
var $el = $('<li>')
$el.html(thingy);
I ended up doing this in the end based off of this stack overflow answer
dpd.things.get(function(result, error) {
console.log(result);
$.each(result, function(i,result){
content = '<p id=" ' + result.name + ' ">'
+ result.name + '</p>' + '<p>' + result.about +
'</p>' + '<p>' + result.id + '</p>'
$(content).appendTo("#test");
});
});
I'd like to ask for some help.
I have an external JSON file with an array inside looking like this:
{ "Files": [
{
"fileName": "Trains",
"fileID": "t1"
},
{
"fileName": "Planes",
"fileID": "p1"
},
{
"fileName": "Cars",
"fileID": "c1"
}
]}
I'm trying to use this data ultimately to fill a dropdown select menu in an XHTML page whilst using JavaScript to write it.
So far I've got the following but can't now figure out where I'm going wrong for the final hurdle. Any pointers on what I'm not understanding appreciated, thanks.
function fileDropdown() {
var options = "";
$.getJSON(
"json/files.json",
function(result) {
//find the array and do seomthing
$.each(result.Files, function(key, val) {
options += '<option value="' + val.fileID + '">' + val.fileName + '</option>';
});
}
);
document.write("<select>"+options+"</select>");
}
Try this:
function fileDropdown()
{
$.getJSON("json/files.json", function(result) {
//find the array and do seomthing
var options = "";
$.each(result.Files, function(key, val) {
options += '<option value="' + val.fileID + '">' + val.fileName + '</option>';
});
var select = $('<select/>');
select.append(options);
$(document.body).append(select);
});
}
Thanks, solved the issue now. Would upvote you but require more reputation.
I used
$.each(result.Files, function(file) {
selectElement.append($('<option value="' + this.fileID + '">' + this.fileName + '</option>'));
$.getJSON("json/files.json", ...) means "take window.location, append json/files.json and then send a GET request with this URL".
To fix this, you can use an absolute file: URL. But your browser will probably refuse to load the file for security reasons.
The alternative is to make your web server send the file to the browser when it requests the above URL.