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 );
Related
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?
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/>')
])
);
}
});
});
});
If I have the following html added statically the CSS style is applied correctly
HTML:
<li class="connector">
<a href="#">
<img src="css/images/temp/connector2.png" alt="" width="192" height="192">
<span class="sr-only">box</span>
</a>
</li>
However if I do the following in Javascript to dynamically render the HTML the CSS does not seem to get applied.
JavaScript:
element.innerHTML += "<li class='connector'>" +
"<a href = '/connector/" + i + "'>" +
"<img src ='/" + i + "/background' />" +
"<span class='sr-only'>" + $.get("/" + i + "/getName") +"</span>" +
"</a>" +
"</li>";
The list shows, but without the CSS styling.
Any suggestions?
"<span class='sr-only'>" + $.get("/" + i + "/getName") +"</span>" +
get is asynchronous method. This addition is wrong.
The problem was with how I was using the Isotope Javascript library. The way I was adding the content was bypassing it.
After reading their documentation, I was able to get it to work properly.
I used the following instead
$.get("/connectorCount", function(data){
for (var i = 0; i < data; i++)
{
var $newItems = $('<li class="connector"> <img src = "/' + i + '/background" /> <span class="sr-only">' + $.get("/" + i + "/getName") + '</span></li>');
$('.connectors').isotope('insert', $newItems);
}
refreshSearch(data);
});
I have a textarea that will contains a code entered by user and I want to get that code and scan it with jQuery to get the value inside a custom tag called setting then add this value to an input so the user will be able to change the value inside setting tag without touching the code. I was able to get the values and add them inside the inputs but I couldn't update the code with the new values.
HTML CODE :
<div id='tab-1'>
<textarea id='template-code' cols='67' rows='27'></textarea>
<button id='submit-code'>Submit Code</button>
</div>
<div id='tab-2' class='unactive'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update-code'>Update Code</button>
</form>
</div>
CSS CODE :
.unactive {
display: none
}
jQuery CODE :
$('#template-code').change(function (){
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$(document).on('click', '#submit-code', function (){
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i){
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="'+setting_id+'" name="'+setting_id+'" type="text" value="'+setting_std+'"><br>';
});
if(code !== ''){
$('#result').html(code);
}
});
// Update old data with the new one
$(document).on('click', '#update-code', function (){
new_data = $( "#settings-form" ).serializeArray();
$.each( new_data, function( i, new_field ) {
var start_key = "id='"+new_field.name+"'>",
end_key = '</setting>',
start = template_code.indexOf(start_key),
end = template_code.indexOf(end_key);
text = template_code.substring(start + start_key.length, end);
// THE PROBLEM IS HERE
// I want the variable template_code to contains the new value not the old one so I used replace but it seems that it doesn't work
template_code.replace(text, new_field.value);
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
This is an example of the theme code that will be added inside the textarea :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
</div>
</head>
<body>
</body>
</html>
To understand my issue please enter to this JsFiddle and copy the code above then put it inside the textarea and click submit code, you will get two inputs the content of those inputs come from these two tags :
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
I want when the user change the value of inputs and click "update code" to change the value of setting tag inside the entire code.
Try this and see if it's what you're looking for:
HTML
<div id='tab-1'>
<textarea id='template' cols='67' rows='27'></textarea>
<button id='submit'>Submit Code</button>
</div>
<div id='tab-2'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update'>Update Code</button>
</form>
</div>
JavaScript:
function wrap(data) {
var string = '';
var i, l;
string += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
string += "<!DOCTYPE html>\r\n";
string += "<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>\r\n";
string += " <head>\r\n";
string += " <b:include data='blog' name='all-head-content'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>\r\n";
string += " <title><data:blog.pageTitle/></title>\r\n";
string += " </head>\r\n";
string += " <body>\r\n";
string += " <div id='option-panel' style='display:none!important'>\r\n";
for (i = 0, l = data.length; i < l; i++)
string += " " + data[i].toString() + "\r\n";
string += " </div>\r\n";
string += " </body>\r\n";
string += "</html>\r\n";
return string;
}
$("#submit").on('click', function() {
var virtual = document.createElement("div");
var temp = '';
virtual.innerHTML = $("#template").val();
$(virtual).find('setting').each(function(i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
temp += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (temp !== '')
$('#result').html(temp);
});
$("#update").on('click', function(event) {
var temp = [];
event.preventDefault();
$("#result").find("input").each(function() {
temp.push("<setting id=\"" + this.id.toString() + "\">" + this.value.toString() + "</setting>");
});
$("#template").val(wrap(temp));
});
I believe that does what you're looking for? Even though you're using jQuery, I think you ended up making it a lot harder than it had to be. I used a virtual node to quickly/easily find and pull ONLY the setting tag from the textarea on submit (down and dirty, I suppose?).
I removed the styles and whatnot since it was interfering with rapid testing, and you'll need to apply proper sanity checking/validation against user input.
Edit: Updated answer to include a ghetto wrapping function to elucidate the concept. I would not recommend using it as is, but instead utilizing a real template, which would require work outside the scope of this question.
Most recent JSFiddle after editing: http://jsfiddle.net/zo3hh2ye/6/
Here's another version of the code. I saved the new values in an array and then replaced them with the existing values in the textarea text. Give a try and see if that solves your problem.
Script :
<script type="text/javascript">
$('#template-code').change(function () {
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$('#submit-code').click(function () {
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (code !== '') {
$('#result').html(code);
}
});
// Update old data with the new one
$('#update-code').click(function () {
new_data = $("#settings-form").serializeArray();
$(template_code).find('setting').each(function (i) {
template_code = template_code.replace("<setting", "").replace("id='" + $(this).attr("id") + "'>", "").replace($(this).html(), "{" + i + "}").replace("</setting>", "");
});
$.each(new_data, function (i, new_field) {
template_code = template_code.replace("{" + i + "}", "<setting id='" + new_field.name + "'>" + new_field.value + "</setting>");
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
</script>
HTML Template :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>text1</setting>
<setting id='search_icon'>text2</setting>
</div>
</head>
<body>
</body>
</html>
I couldn't replace the text 'on' in the template you provided, not sure if it has something to do with some reserved key word but everything else works fine.
I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.