Field Length Always = 1 - javascript

Following the Reuters Ajax Solr tutorial I'm having an issue getting a fields length.
The issue is with the 'template' but I believe it may stem from another js file.
THE TUTORIALS 'TEMPLATE'
template: function (doc) {
var snippet = '';
if (doc.text.length > 300) {
snippet += doc.dateline + ' ' + doc.text.substring(0, 300);
snippet += '<span style="display:none;">' + doc.text.substring(300);
snippet += '</span> more';
}
else {
snippet += doc.dateline + ' ' + doc.text;
}
var output = '<div><h2>' + doc.title + '</h2>';
output += '<p id="links_' + doc.id + '" class="links"></p>';
output += '<p>' + snippet + '</p></div>';
return output;
},
MY 'TEMPLATE'
template: function (doc) {
var snippet = '';
if (doc.Solution.length > 200) {
snippet += doc.Solution.substring(0, 200) + ' ' + doc.date;
snippet += '<span style="display:none;">' + doc.Solution.substring(200);
snippet += '</span> more';
}
else {
snippet += doc.Solution.length + '<br>' + doc.date + '';
}
var output = '<div><br><b>' + doc.Problem + '</b><br>';
output += '' + snippet + '';
output += ' ID #' + doc.id + '</div>';
return output;
},
This section is supposed to allow for a 'more' button if a field is over a certain length. With my template, this is my output:
My 'Solution' field is a long text field which in my schema for solr (7.5) is defined as text_general.
I have tried String() and .toString but those gave me issues as well.
I'm very new to CS as a whole but it seems that my field is behaving as an array or boolean?
In the tutorial they have an older version of solr but the field they get the length on is text_general as well. I'm not exactly sure where I should look next.
PS: this is how the code is structured in the tutorial, a friend of mine was confused because it doesn't all seem to be best practices.
I my setup differs from the tutorial in a few ways, I use my version of JQuery (v3.3.1) and they use some style sheets that I do not.
The <head> of my html doc:
<title>Testing Solr</title>
<meta charset="UTF-8">
<!--style sheets and links in tutorial source code--
<link rel="stylesheet" href="reuters.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css">
<!--my downloaded copy of jquery-->
<script src="script/jquery.js"></script>
<!-- mentioned in tutorial -->
<script src="script/our.js"></script>
<script src="script/Core.js"></script>
<script src="script/AbstractManager.js"></script>
<script src="script/Manager.jquery.js"></script>
<script src="script/Parameter.js"></script>
<script src="script/ParameterStore.js"></script>
<script src="script/AbstractWidget.js"></script>
<script src="script/ResultWidget.js"></script>
Switched to using their links other than the reuters.css, still displaying 1.
Using console.log(doc.Solution); this is indeed acting as an array.
["solution to unlock "]
0: "solution to unlock "
length: 1
__proto__: Array(0)
Adding console.log(doc.text); to the tutorial's ResultWidget.js returns plain text to the console. Whats a likely reason my field is being read as an array when theirs is read as a string?

Related

Web app - Google sheets - html table with input field

We have a requirement to track and audit production, essentially we have lots of orders of which we seem to be loosing some of our products on the way (spoils etc).
To stop this we have now placed orders on to google sheets and listed a quantity of how many there should be, an employee then would write in how many was recieved.
On the web app I want to show the table and have a field where the employee can enter the count,
So if I had a google sheet I might have in column A [Product Name] column b [Start Quanity] and in column C [Counted Quantity]
On the web app it will show all 3 columns but allow the user to enter the count into the [Counted Quantity] column.
Is this possible? (Assuming I either need a input field within the html table or an editable table?
Thanks
This will get all of the data in your spread but you can only edit the last column. It's built as a dialog but one could easily change that to a webapp.
I had some problems with scopes so I thought you might need them. If you don't know what do to with these then skip them and come back if you have a problem.
"oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/script.container.ui"]
ordercounts.gs:
function getOrders() {
var ss=SpreadsheetApp.getActive();
var osh=ss.getSheetByName("Orders");
var org=osh.getDataRange();
var vA=org.getValues();
var rObj={};
var html='<style>th,td{border: 1px solid black}</style><table>';
vA.forEach(function(r,i){
html+='<tr>';
r.forEach(function(c,j){
if(i==0){
html+=Utilities.formatString('<th>%s</th>',c);
}else if(j<r.length-1){
html+=Utilities.formatString('<td>%s</td>', c);
}else{
html+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + c + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
});
html+='</tr>';
});
html+='</table>';
return html;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.getActive();
var sht=ss.getSheetByName("Orders");
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function launchOrdersDialog(){
var userInterface=HtmlService.createHtmlOutputFromFile('orders');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "OrderCounts");
}
orders.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(hl){
console.log('Getting a Return');
$('#orders').html(hl);
})
.getOrders();
});
function updateSS(i,j) {
var str='#txt' + String(i) + String(j);
var value=$(str).val();
var updObj={rowIndex:i,colIndex:j,value:value};
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(updateSheet)
.updateSpreadsheet(updObj);
}
function updateSheet(data) {
//$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
</head>
<body>
<div id="orders"></div>
</body>
</html>
Here's what the tool looks like:
All you have to do is enter the updated count and hit enter and the spreadsheet changes.

Unexpected token u in JSON at position 0 i'm trying to do a plugin

I have a problem(or problems) with my code, when I'm trying running the script in the developer kit trows the error
unexpected token u in JSON at position 0...
funciones.js
$(document).ready(function (){
$("#btn1").click(function(){
$.ajaxSetup({ cache: false });
var url = "productos.json";
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
for (var team in data) {
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + data[team].producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' +data[team].producto.precio + '<br/>';//precio
html += '<b>Marca: </b>' +data[team].producto.marca + '<br/>';
html += '<b>Presentación: </b>' + data[team].producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + data[team].producto.contenido + '<br/></div>';
$("#div1").append(html);
}
}));
});
});
function block(){
document.getElementById("btn1").disabled = true;
}
productos.json
[
{
"nombre":"Coca-Cola",
"precio":30,
"marca": "Cocacola",
"presentacion":"Familiar grande",
"contenido":"3Lt."
},
{
"nombre":"Coca-Cola",
"precio":25,
"marca": "Cocacola",
"presentacion":"Familiar",
"contenido":"2.5Lt."
},
{
"nombre":"Coca-Cola",
"precio":15,
"marca": "Cocacola",
"presentacion":"individual",
"contenido":"1Lt."
}
]
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="funciones.js" language="javascript" type="text/javascript"></script>
<script type="text/javascript" src="productos.json"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="stilo.css">
</head>
<body>
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1" onclick="block()" type="button">Team location</button>
</div>
</body>
</html>
What is the problem here?Thanks in advance
There are several problems in your code. I have modified your code into a plunkr here You should visit the working plnkr to find what was corrected however I will put some snippets here also.
The line below does not do anything.
var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){
The actual ajax call was missing so I added it
$.ajax({
url: url
}).done(function(myData){
//your code here
}
Then the loop
html = 'Nombre: ' + data[team].producto.nombre + '[\n]';
Here data is an array so it needs to be treated as an array. Further each array item itself is producto.
So this is corrected to
for (var i = 0; i < data.length ; i++) {
var producto = data[i];
var html = []; //variable html
html = '<div class="item"><b>Nombre: </b>' + producto.nombre + '<br/>[\n]';
html += '<b>Precio: $</b>' + producto.precio + '<br/>'; //precio
html += '<b>Marca: </b>' + producto.marca + '<br/>';
html += '<b>Presentación: </b>' + producto.presentacion + '<br/>';
html += '<b>Contenido: </b>' + producto.contenido + '<br/></div>';
$("#div1").append(html);
}
There are several issues:
url.responseText is undefined, and so the error complains on the first character of that, i.e. the u of undefined. Look at how you defined url and notice how that does no have responseText.
There is no Ajax call in your code. Use $.getJSON for this.
Do not use JSON.parse nor JSON.stringify: they only make things worse. jQuery will have done the conversion for you already.
If html is supposed to be a string, then don't initialise it as an array with [].
the onclick attribute references a function block that is not in the global scope.
Either add a click handler via code, or via the onclick attribute, but not both. So combine the code in one single click handler via one method.
The property producto does not exist in your JSON, so all the references to it will fail. Remove that property from your code, unless your JSON is different from what you have in the question
Other remarks:
You mix jQuery and non-jQuery syntax. When you have jQuery, use it. So not document.getElementById().
[\n] is a strange thing to output. I would remove that.
The loop for (var team in data) can be written with of instead of in, that way team will be the object, not the index, which makes the rest of your code simpler.
A button element doesn't need a type="button" attribute
Here is code that corrects all these issues:
HTML:
<div>
<div>Prueba basica de archivos</div>
<div id="div1"></div>
<button id="btn1">Team location</button>
</div>
JavaScript:
$(document).ready(function (){
$("#btn1").click(function(){
$(this).disabled = true;
$.ajaxSetup({ cache: false });
$.getJSON("productos.json").done(function(data) {
for (var team of data) {
$("#div1").append(
$('<div>').addClass('item').append([
$('<b>').text('Nombre'), team.nombre, $('<br>'),
$('<b>').text('Precio: $'), team.precio, $('<br>'),
$('<b>').text('Marca: '), team.marca, $('<br>'),
$('<b>').text('Presentación: '), team.presentacion, $('<br>'),
$('<b>').text('Contenido: '), team.contenido, $('<br/>')
])
);
}
});
});
});

Accessing Wikipedia API with JSONP

I've been trying for the last few days to make my code work, but I just can't find the problem.
I want to make communication with the Wikipedia server and get their JSON API so I can make a list of items corresponding to the input value of searchInput.
I've been looking into JSONP, finding in the end that I can add "&callback=?" to my API request and that it should work.
Now, even though I've added it, the communication still isn't happening.
I've noticed that the console on codepen.io returns "untitled" for a moment while initializing the code after processing the "#searchInput" input.
Perhaps the problem is in my for...in loop.
Do you have any idea what I should do?
The link to my code: http://codepen.io/nedsalk/pen/zqbqgW?editors=1010
(JQuery is already enabled in the "settings" menu)
If you prefer the .html edition of the code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Object Oriented JavaScript </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"> </script>
</head>
<body>
<h1> Wikipedia viewer </h1>
Go random!
<form>
<input type="text" name="searchInput" id="searchInput" placeholder="Search Wikipedia"
onkeydown = "if (event.keyCode == 13)
document.getElementById('submit-button').click()"/>
<input type="submit" id="submit-button"/>
</form>
<div id="list"></div>
<script>
$(document).ready(function() {
$("#submit-button").on("click",function (){
var input=$("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?',
function(API){
$("#list").empty();
for (var id in API.query.pages)
{if(API.query.pages.hasOwnProperty(id){
$("#list").html('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">'
+'<div id="searchList">'
+ "<h2>" + id.title + "</h2>"
+ "<br>"
+ "<h3>" + id.extract + "</h3>"
+ "</div></a><br>")
}}
})
})
})
</script>
</body>
</html>
You have several issues in your code:
you should hook to the submit event of the form, not the click of the button, and use event.preventDefault() to stop the submission.
you loop through the keys of the returned object and attempt to access properties of those strings, instead of using the keys to access the underlying properties.
you set the html() in each loop, so only the final item will be visible. You should use append() instead.
Try this:
$("form").on("submit", function(e) {
e.preventDefault();
var input = $("#searchInput").val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?', function(response) {
var pages = response.query.pages;
$("#list").empty();
for (var id in pages) {
$("#list").append('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">' +
'<div id="searchList">' +
"<h2>" + pages[id].title + "</h2>" +
"<br>" +
"<h3>" + pages[id].extract + "</h3>" +
"</div></a><br>")
}
});
});
Working example

How show the normal text read from a file

I'm with the following problem: I'm brazilian, and here we use strange characters like 'ç' or 'ã'. So, I'm programming for web and when I read the text file and show its content, it replaces the strange characters for '?'.
EDITED:
I have this code:
<script type="text/javascript">
$(getImages);
function getImages() {
$.getJSON("/home/ListImagesProducts", showImages);
}
function showImages(data) {
$("#directoryImages").append("<ul id = 'productImages'>");
for (i = 0; i < data.length; i++) {
var directories = data[i];
$("#directoryImages ul").append("<li><img src='../Content/images/Products/" + directories.ImageName + "' /><div class = 'description'> ççç" + directories.DescriptionName + "</li>");
}
//$("#directoryImages").append("</ ul>");
}
The 'ççç' before the 'directories.DescriptionName' are shown normainly. I'm reading the text from a notepad file. I already put 'UTF-8'.
How can I show the normal text read from the file?
You need the UTF-8 character encoding for your document
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>My page</title>
</head>
<body>
<p>çãšđčćž</p>
</body>
</html>
theremore if you use some text editor (like Notepad++) make sure to set encoding:
Encode in UTF-8 Without BOM
Additionally you have some errors in your code. You messed up with ' and " and you don't have the closing </div>
src='../Content/images/Products/" + directories.ImageName + "' /><div class = 'description'> ççç" + directories.DescriptionName + "</li>"
should be:
src='../Content/images/Products/' + directories.ImageName + ' /><div class="description"> ççç ' + directories.DescriptionName + '</div></li>'
Instead of using .append() inside a for loop (which is terribly slow) create a string, populate it inside the for loop and than append it only once:
var ul = "<ul id='productImages'>";
for (i=0; i<data.length; i++) {
var directories = data[i];
ul += "<li><img src='../Content/images/Products/" + directories.ImageName + "' /><div class = 'description'> ççç" + directories.DescriptionName + "</div></li>";
}
ul += "</ul>";
$("#directoryImages").append( ul );

JSon and Jquery Accordion

This is driving me freaking BATTY as hell.
This is essentially what I am trying to accomplish.
You'll see the Json there are a 2 different departments "Office" and "Stockroom"
What I am trying to accomplish is to arrange everyone by the department they are in. The problem with this is that the HTML needs to look something like this
<h3>Section 1</h3>
<div>
<p>
First Paragraph
</p>
<p>
Second Paragraph
</p>
<p>
Third Paragraph
</p>
</div>
But unfortunately I cannot seem to get the </div> tag in the right spot at the end of the last paragraph of each section
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="http://jqueryui.com/themes/base/jquery.ui.all.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.accordion.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var contacts = [{"displayname":"Bruce Lee","email":"Bruce.lee#karate.com","department":"stockroom"},
{"displayname":"Your Momma","email":"Your.Momma#Yourmom.com ","department":"stockroom"},
{"displayname":"Bob","email":"Bob#bob.com ","department":"Office"},
{"displayname":"Cathy","email":"Cathy#Cathy.com ","department":"Office"},
{"displayname":"mike","email":"mike#Cathy.com ","department":"Office"},
{"displayname":"scott","email":"scott#Cathy.com ","department":"Office"}
];
var contacts2 = contacts;
var r = 1;
var lastvalue = 'blah';
for(var i=0; i <=contacts.length; i++)
{
if(contacts[i].department != null)
{
if(lastvalue != contacts[i].department)
{
if(i<1)
{
$('#accordion').append('</div><h3>' + contacts[i].department + '</h3>');
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
}else{
$('#accordion').append('<h3>' + contacts[i].department + '</h3>');
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
}
}else{
$('#accordion').append('<p>' + contacts[i].displayname + '</p>');
}
lastvalue = contacts[i].department;
r++;
}
}
});
$(function() {
$( "#accordion" ).accordion();
});
</script>
</head>
<body>
<div id="contactlist">
<div id="accordion">
</div>
</div>
</body>
</html>
You might want to change this to a jquery each loop and work with json objects directly inside it. The reason you were getting an accordion level each time was due to your loop inserting a h3 every time. I've supplied code to get you pretty much what you need.
edit:
Here is a link to my forked jsfiddle => http://jsfiddle.net/TTV6d/12/
Hope this helps
var departmentlist=new Array();
$.each(contacts, function(i,contact) {
//insert the departments
if (contact.department != null && $('#' + contact.department).length == 0) {
$('#accordion').append('<h3 id='+ contact.department +'>' + contact.department + '</h3>');
departmentlist.push(contact.department);
}
//insert contacts in the accordion
$('#' + contact.department).after('<p>' + contact.displayname + '</p>');
});
$.each(departmentlist, function(i,list) {
$("#" + list).nextUntil("h3").wrapAll("<div></div>");
});
First, be aware that browsers will generally attempt to normalize markup appended to the document: (http://jsfiddle.net/EVjaq/)
$('#container').append('<div><p>Testing</p>'); // no `</div>`
console.log($('#container').html()); // `<div><p>Testing</p></div>`
So, the open <div> in this line will be closed at the end for you, before the next <p> is appended:
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
To avoid this, you can store all of the HTML in a variable, concatenating segments together, and append it to the DOM only once it's done. Or, you can store the <div> and append to that, which can make the conditionals a bit simpler:
var lastvalue = null,
lastdiv = null;
for (var i = 0; i <= contacts.length - 1; i++) {
if (contacts[i].department != null) {
if (lastvalue != contacts[i].department) {
$('#accordion').append('<h3>' + contacts[i].department + '</h3>');
// remember `<div>`
lastdiv = $('<div>').appendTo('#accordion');
}
// append to the `<div>` directly rather than `#accordion`
// also, skip the `else` so you don't have to type this twice
lastdiv.append('<p>' + contacts[i].displayname + '</p>');
lastvalue = contacts[i].department;
r++;
}
}

Categories

Resources