I'm trying to get the jQuery template feature working but have finally come to a dead end. From all my investigation the code listing below should work and I expect to get:
file1.txt, 123456, 2012-01-01
file2.txt, 234567, 2012-01-02
file3.txt, 345678, 2012-01-03
but instead I get
, ,
, ,
, ,
Clearly the library is loading and the code is running but for some reason it will not pick up the data elements. The code behaves the same regardless of the browser. I've tried compiling the template and not, each with the same results.
I'm sure that I'm missing something simple, but I've been pulling my hair out for about 8 hours staring at examples (and I've not that much hair left!). Thanks in advance for any assistance.
<html lang="en">
<head>
<title>jQuery Template Test</title>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="inc/jquery.tmpl.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var exampleData = [
{ name: "file1.txt", size: "123456", date: "2012-01-01" },
{ name: "file2.txt", size: "234567", date: "2012-01-02" },
{ name: "file3.txt", size: "345678", date: "2012-01-03" }
];
var markup = "<li>${name}, ${size}, ${date}</li>";
$.template( "exampleTemplate", markup );
$.tmpl("exampleTemplate", exampleData).appendTo("#target");
});
</script>
</head>
<body>
<ul id="target"></ul>
</body>
</html>
I had the same problem with JSP: Use \$ to escape EL expression
Related
I am new to programming and recently began learning Javascript, I have a problem that appeared in few exercises that I made. I searched the site for more information but have not found a solution for my problem. I apologize in advance for my bad english and if this is not the right place or the right way to ask this question because this is my first post in Stackoverflow.
Currently practicing HTML templates. Assuming that the code is correct, I'm not sure where I'm wrong. Loading code into the browser and Handlebars gives me an error: "Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined". I tried to debug and saw that when I tried to take a value from date object it gives back undefined. In previous exercise had a similar problem in which I tried to read JSON object and did not manage to parse it and returned again undefined. Can you help me, I am stuck on this problem for some time.
var data = {
animals: [{
name: 'Lion',
url: 'https://susanmcmovies.files.wordpress.com/2014/12/the-lion-king-wallpaper-the-lion-king-2-simbas-pride-4685023-1024-768.jpg'
}, {
name: 'Turtle',
url: 'http://www.enkivillage.com/s/upload/images/a231e4349b9e3f28c740d802d4565eaf.jpg'
}, {
name: 'Dog'
}, {
name: 'Cat',
url: 'http://i.imgur.com/Ruuef.jpg'
}, {
name: 'Dog Again'
}]
}
window.onload = function() {
var htmlTemplate = document.getElementsByClassName('container-template').innerHTML;
var template = Handlebars.compile(htmlTemplate);
for (let x of data.animals) {
if (x.hasOwnProperty('url')) { //x.url
x.hasUrl = true;
} else {
x.hasUrl = false;
}
}
document.getElementsByClassName('container').innerHTML = template(data);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Animals & Batman</title>
</head>
<body>
<div class="container">
</div>
<script class="container-template" type="text/x-handlebars-template">
<h1>Animals</h1>
{{#each animals}}
{{#if hasUrl}}
<li>
See a {{name}}
</li>
{{else}}
<li>
No link for {{name}}, here is Batman!
</li>
{{/if}}
{{/each}}
</script>
<script src="../handlebars-v4.0.5.js" charset="utf-8"></script>
<script src="../jquery-3.1.0.js" charset="utf-8"></script>
<script src="./main.js" charset="utf-8"></script>
</body>
</html>
document.getElementsByClassName returns an array of elements, not a single one - since multiple elements on a page can have the same class.
What you probably want is to use the id instead of class:
<script id="container-template" type="text/x-handlebars-template">
var htmlTemplate = document.getElementById('container-template').innerHTML;
I tried using Mention.js from this.
My Search.html contains,
<!DOCTYPE html>
<html>
<body>
<div>
<textarea id="try"></textarea>
</div>
<script type="text/javascript" src="http://jakiestfu.github.io/Mention.js/javascripts/bootstrap-typeahead.js">
$('#try').mention({
delimiter: '#',
users: [{
username: "ashley"
}, {
username: "roger"
}, {
username: "frecklefart123"
}]
});
</script>
</body>
</html>
The box returns no result. Any help in pointing my mistake is appreciated. Thanks.
P.S This is pseudocode, the actual usage is in my rails app in search.html.erb which has Typeahead dependancy.
As the documentation of Mention.js
Dependencies
jQuery ,
Typeahead
so you should use
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://jakiestfu.github.io/Mention.js/javascripts/bootstrap-typeahead.js"></script>
then the plugin
<script type="text/javascript">(function(e){e.fn.extend({mention:function(t){this.opts={users:[],delimiter:"#",sensitive:true,queryBy:["name","username"],typeaheadOpts:{}};var n=e.extend({},this.opts,t),r=function(){if(typeof e=="undefined"){throw new Error("jQuery is Required")}else{if(typeof e.fn.typeahead=="undefined"){throw new Error("Typeahead is Required")}}return true},i=function(e,t){var r;for(r=t;r>=0;r--){if(e[r]==n.delimiter){break}}return e.substring(r,t)},s=function(e){var t;for(t in n.queryBy){if(e[n.queryBy[t]]){var r=e[n.queryBy[t]].toLowerCase(),i=this.query.toLowerCase().match(new RegExp(n.delimiter+"\\w+","g")),s;if(!!i){for(s=0;s<i.length;s++){var o=i[s].substring(1).toLowerCase(),u=new RegExp(n.delimiter+r,"g"),a=this.query.toLowerCase().match(u);if(r.indexOf(o)!=-1&&a===null){return true}}}}}},o=function(e){var t=this.query,r=this.$element[0].selectionStart,i;for(i=r;i>=0;i--){if(t[i]==n.delimiter){break}}var s=t.substring(i,r),o=t.substring(0,i),u=t.substring(r),t=o+n.delimiter+e+u;this.tempQuery=t;return t},u=function(e){if(e.length&&n.sensitive){var t=i(this.query,this.$element[0].selectionStart).substring(1),r,s=e.length,o={highest:[],high:[],med:[],low:[]},u=[];if(t.length==1){for(r=0;r<s;r++){var a=e[r];if(a.username[0]==t){o.highest.push(a)}else if(a.username[0].toLowerCase()==t.toLowerCase()){o.high.push(a)}else if(a.username.indexOf(t)!=-1){o.med.push(a)}else{o.low.push(a)}}for(r in o){var f;for(f in o[r]){u.push(o[r][f])}}return u}}return e},a=function(t){var r=this;t=e(t).map(function(t,i){t=e(r.options.item).attr("data-value",i.username);var s=e("<div />");if(i.image){s.append('<img class="mention_image" src="'+i.image+'">')}if(i.name){s.append('<b class="mention_name">'+i.name+"</b>")}if(i.username){s.append('<span class="mention_username"> '+n.delimiter+i.username+"</span>")}t.find("a").html(r.highlighter(s.html()));return t[0]});t.first().addClass("active");this.$menu.html(t);return this};e.fn.typeahead.Constructor.prototype.render=a;return this.each(function(){var t=e(this);if(r()){t.typeahead(e.extend({source:n.users,matcher:s,updater:o,sorter:u},n.typeaheadOpts))}})}})})(jQuery)</script>
or just download the Mention.js file and link it to your code
and then
<script>
// run your code here
</script>
$('#try').mention({...)};it should be in $( document ).ready().
I am trying to parse some form data to produce JSON data to send in an ajax request. The following HTML is an oversimplified version of my code. I'm using APS.Net MVC4 and my rendered view produces the following HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div class="test-class" data-my-attribute="1"></div>
<div class="test-class" data-my-attribute="2"></div>
<div class="test-class" data-my-attribute="3"></div>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
jsonObj = [];
$(".test-class").each(function () {
var myAttribute = $(this).data('my-attribute');
item = {}
item["MyAttribute"] = myAttribute;
jsonObj.push(item);
});
var data = { SomeOtherData: 1234, MyAttribs: jsonObj };
console.log(JSON.stringify(data));
});
</script>
</body>
</html>
In Chrome the output in the console is output as expected ...
{
"SomeOtherData": 1234,
"MyAttribs": [{
"MyAttribute": 1
}, {
"MyAttribute": 2
}, {
"MyAttribute": 3
}]
}
... but in IE the objects come out as null ...
{
"SomeOtherData": 1234,
"MyAttribs": [null, null, null]
}
I've had a look around and found some other questions that recommend checking that the page has <!DOCTYPE html> in it (which it does) and that doesn't seem to have any effect. I've also read that this should work in from IE8 onward so not sure what's happening.
Does anyone know why the objects are appearing as nulls in IE?
What is the best cross-browser solution to this?
Thanks,
Gavin
The only weird thing I see is that:
item = {}
Should be:
var item = {}; // 'var' and semicolon
Sometimes IE is quite strict..
on my case use as #palvo sayed console.dir(obj)
other alternative is JSON2 from douglascrockford
I stripped down my code to a simple page including the flog plugin and jquery files, but am still unable to get the flot graphs to render in IE 7 and 8. I may be missing something, but I am using flot 8.1(7.0 worked fine).
I cut it down to a simple page with the what I assume are the necessary scripts. Thank you for any help you can provide!
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script type='text/javascript' src='js/plugins/jquery/jquery-1.9.1.min.js'></script>
<script type='text/javascript' src='js/plugins/jquery/jquery-ui-1.10.1.custom.min.js'></script>
<script type='text/javascript' src='js/plugins/jquery/jquery-migrate-1.1.1.min.js'></script>
<script type='text/javascript' src='js/plugins/other/excanvas.js'></script>
<script type='text/javascript' src='js/plugins/flot/jquery.flot.js'></script>
<script type='text/javascript' src='js/plugins/flot/jquery.flot.stack.js'></script>
<script type='text/javascript' src='js/plugins/flot/jquery.flot.pie.js'></script>
<script type='text/javascript' src='js/plugins/flot/jquery.flot.resize.js'></script>
</head>
<body class="smw ssDark">
<div class="header">
<div id="chart_activity" style="height:500px;" >
</div>
</div>
<script>
$("document").ready(function(){
if($("#chart_activity").length > 0){
var stuff = [], contacts = [];
for (var i = 0; i < 7; i += 1) {
stuff.push([i, parseInt(Math.random() * 30)]);
contacts.push([i, parseInt(Math.random() * 30)]);
}
$.plot($("#chart_activity"), [ { data: stuff, label: "stuff"}, { data: contacts, label: "contacts"}], {xaxis: {show: true}, yaxis: { show: true}});
}
});
</script>
</body>
</html>
Edit: Forgot to mention, I get the following error in IE console:
SCRIPT5007: Unable to get property 'fillStyle' of undefined or null reference
excanvas.js, line 230 character 5
Sorry for coming back with the answer slowly. Apparently the downloaded version of excanvas that I had, was somehow different from the one the came with Flot. Once I switched them out everything worked fine in IE 7/8.
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js",
function(json) {
var ticketPriceArray=[json.tickets[0].price, json.tickets[1].price,
json.tickets[2].price, json.tickets[3].price, json.tickets[4].price,
json.tickets[5].price];
alert(json.tickets[0].type);
var inputWord =$("#keyword").val();
if (inputWord=="A"){$("#result").text(ticketPriceArray[0]);}
if (inputWord=="B"){$("#result").text(ticketPriceArray[1]);}
if (inputWord=="C"){$("#result").text(ticketPriceArray[2]);}
if (inputWord=="D"){$("#result").text(ticketPriceArray[3]);}
if (inputWord=="E"){$("#result").text(ticketPriceArray[4]);}
if (inputWord=="F"){$("#result").text(ticketPriceArray[5]);}
});
});
});
</script>
Here is "ticketPriceInArray.js"
{
"tickets":[
{
"type":"A Ticket",
"price":220,
},
{
"type":"B Ticket",
"price":180,
},
{
"type":"C Ticket",
"price":120,
},
{
"type":"D Ticket",
"price":100,
},
{
"type":"E Ticket",
"price":80,
},
{
"type":"F Ticket",
"price":50,
}
]
}
This is a simple html where when the corresponding text inputed, the corresponding ticket price will show in the html after a button-click. All the ticket info is stored in a .json file named "ticketPriceInArray.js" and I have been trying to read it using $.getJSON(), but unfortunately I haven't been able to get any success. The weird thing is I didn't get any warning on anything so I couldn't fix it. Please see if you can give me any suggestions. Thank you.
By adding an AJAX error handler, I received this
"parsererror" SyntaxError: Unexpected token }
The problem is the trailing commas after each price property.
The following example is working fine in FF and Chrome with the exact JSON you provided. In IE you will have to remove the commas after the prices, as Phil already said.
In my test both the test.html and test.js were placed in my apache server root; viewing the files directly from my desktop into my browser didn't work apparently due to security restrictions.
<html>
<head></head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("test.js", function(json) {
for (var i in json.tickets) {
var type = json.tickets[i].type;
var price = json.tickets[i].price;
$('#result').append('<span>type: ' + type+ ', price: ' + price + '</span><br />');
}
});
});
});
</script>
<button id="Button1">click me</button>
<div id="result"></div>
</body>
</html>
I suggest you use http://jsonlint.com/ to validate your JSONs; or just rely on a good encoder instead of doing it by hand ;)
A little bit different approach to solving this problem. This is assuming that you aren't changing your ticket prices based on some data that you pass to the url.
ticketPriceInArray.js
{
"A" : 220,
"B" : 180,
"C" : 120,
"D" : 100,
"E" : 80,
"F" : 50
};
main file
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
var ticket_prices = {};
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js", function(returnedJSON) {
ticket_prices = returnedJSON;
$("#result").text( ticket_prices[ $("#keyword").val() ] );
});
});
});
</script>
If there are any considerations (or questions about my assumptions) let me know and I will update based on that.
Assuming the following facts:
you're using firefox
there is no traffic in the network-tab when you click on #Button1
there are no errors logged
... I would like to say:
the element you click on is not $("#Button1")
Are you sure that the element you click on has the ID "Button1" and that there is only one element using that ID ?
Are you running this from a webserver or from your local filesystem?